1.通过侦听器watch来侦听属性
<div id="demo">{{ fullName }}</div>
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
}
}
})
上面代码是命令式且重复的,当有一些数据需要随着其它数据变动而变动时,很容易滥用 watch,通常更好的做法是使用计算属性而不是命令式的 watch 回调。
2.通过计算属性来侦听属性
var vm = new Vue({
el: '#demo',
data: {
firstName: 'Foo',
lastName: 'Bar'
},
computed: {
fullName: function () {
return this.firstName + ' ' + this.lastName
}
}
})
计算属性默认只有getter方法,可以手动设置setter方法
computed:{
fullName:{
set:function(newValue) {
this.firstName = newValue;
},
get:function() {
return this.firstName;
}
}
}