上一节我们知道了,在大括号插值和v-bind指令中,我们可以使用表达式。但是,如果表达式的逻辑太多、或者使用次数很多的时候,会让代码难以维护,使用模版的代码反而不再简单和清晰。
这种情况下,与其使用复杂逻辑的模版,我们应该使用计算属性。
栗子
<div id="example">
<p>Original message: "{{ message }}"</p>
<p>Computed reversed message: "{{ reversedMessage }}"</p>
</div>
var vm = new Vue({
el: '#example',
data: {
message: 'Hello'
},
computed: {// 计算属性
// a computed getter
reversedMessage: function () {
// `this` points to the vm instance
return this.message.split('').reverse().join('')
}
}
})
结果:
Original message: “Hello”
Computed reversed message: “olleH”
2、计算缓存
计算属性是基于他的依赖的缓存的:结合上一个栗子来说,只有message发生变化的时候,reversedMessage才会重新取值;反言之,如果message的值没有发生改变,那么多次访问reversedMessage计算属性,只会立即返回之前的计算结果,而不会再次执行函数。
下面这个栗子中,由于计算属性的函数不涉及任何响应式依赖,因此,这个函数将被缓存,不再第二次执行:
computed: {
now: function () {
return Date.now()
}
}
3、计算setter
这其实是很基础的JS。
计算属性默认定义getter,不过在需要的时候,我们也可以定义setter:
// ...
computed: {
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]
}
}
}
// ...
这样,运行vm.fullName = ‘John Doe’ 时, setter 会被调用, vm.firstName 和 vm.lastName 也会被对应更新。
Watchers
栗子:
<div id="watch-example">
<p>
Ask a yes/no question:
<input v-model="question">
</p>
<p>{{ answer }}</p>
</div>
var watchExampleVM = new Vue({
el: '#watch-example',
data: {
question: '',
answer: 'I cannot give you an answer until you ask a question!'
},
watch: {
// 如果 question 发生改变,这个函数就会运行
question: function (newQuestion) {
this.answer = 'Waiting for you to stop typing...'
this.getAnswer()
}
},
methods: {
getAnswer: function(){
//代码省略
}
}
})
在上面这个栗子中,使用v-model将input内容与属性question绑定,在watch中定义同名属性question,可以对data.question进行“监听”,当question发生变化,这个函数就会被执行,并通过this.getAnswer方法更新answer(这段代码已经省略)。