vue打卡03 day
2475 ワード
Original message: "{{ message }}"
Computed reversed message: "{{ reversedMessage }}"
{{now}}
{{fullName}},{{firstName}}:{{lastName}}
Ask a yes/no question:
{{ answer }}
var example = new Vue({
el:"#example",
data:{
message:'Hello',
firstName:'zou',
lastName:'weijun'
},
computed:{
reversedMessage:function(){
return this.message.split('').reverse().join('')
},
now: function () {
return Date.now()
},
fullName: {
// getter
get: function () {
return this.firstName + ' ' + this.lastName
},
// setter
set: function (newValue) {
var names = newValue.split(' ')
this.firstName = names[0]
this.lastName = names[names.length - 1]
}
}
}
})
var watchExample = new Vue({
el:'#watch-example',
data:{
question:'',
answer:''
},
watch:{
question:function(newQuestion,oldQuestion){
this.answer = 'Waiting for you to stop typing...'
this.debouncedGetAnswer()
}
},
created: function () {
// `_.debounce` Lodash 。
// , yesno.wtf/api
// AJAX 。
// `_.debounce` ( `_.throttle`) ,
// :https://lodash.com/docs#debounce
this.debouncedGetAnswer = _.debounce(this.getAnswer, 500)
},
methods: {
getAnswer: function () {
if (this.question.indexOf('?') === -1) {
this.answer = 'Questions usually contain a question mark. ;-)'
return
}
this.answer = 'Thinking...'
var vm = this
axios.get('https://yesno.wtf/api')
.then(function (response) {
vm.answer = _.capitalize(response.data.answer)
})
.catch(function (error) {
vm.answer = 'Error! Could not reach the API. ' + error
})
}
}
})