本文为大家分享了Vue计算属性的学习笔记,供大家参考,具体内容如下
①模板内的表达式实际上只用于简单的运算,对于复杂逻辑,使用计算机属性。
②基础例子:
rush:xhtml;">
Original message:"{{message}}"
Computed reversed message:"{{reversedMessage}}"
rush:js;">
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('')
}
}
})
这里我们声明了一个计算机属性reversedMessage,我们提供的函数将用作属性vm.reversedMessage的getter。
③计算机缓存 vs Methods
rush:xhtml;">
Reversed message:"{{reversedMessage}}"
rush:js;">
//in component
methods:{
reversedMessage:function(){
return this.message.split('').reverse()/join('')
}
}
可以将同一个函数定义为一个method而不是一个计算机属性。对于最终的结果,两种方式确实是相同的。然而不同的计算机属性是基于它们的依赖进行缓存的。计算属性只有在它的相关依赖发生改变时才会重新求值,这就意味着只要message还没有改变,多次访问reversedMessage计算属性会立即返回之前的计算结果,而不必再次执行函数。 下面的计算属性将不再更新,因为Date.Now()不是响应式依赖:
④computed属性 vs watch属性
rush:xhtml;">
watch:
rush:js;">
var vm = new Vue({
el:"#demo",data:{
firstName:"Foo",lastName:"Bar",fullName:"Foo Bar"
},watch:{
firstName:function(val){
this.fullName = val + '' + this.lastName
},lastName:function(val){
this.fullName = this.firstName + '' +val
}
}
})
computed:
rush:js;">
var vm = new Vue({
el:'#demo',data:{
firstName:'Foo',lastName:'Bar'
},computed:{
fullName:function(){
return this.firstName + ' ' + this.lastName
}
}
})
⑤计算setter:
计算属性默认只有getter,不过在需要是可以提供一个setter:
rush:js;">
// ...
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
当想要在数据变化相应时,执行异步操作或开销较大的操作,这是很有用的。
rush:xhtml;">
Ask a yes/no question:
{{ answer }}
rush:xhtml;">
在这个示例中,使用watch选项允许我们执行异步操作,限制我们执行该操作的频率,并在得到最终结果前,设置中间状态,这是计算属性无法做到的。