Vue监听属性和计算属性
在vue中有监听属性:watch
计算属性:computed两个
watch使用方法为:监听data中的数据,产生一个回调会有新旧数值,可以对数据进行监听(不建议使用)
var vm = new Vue({
el: '#demo',
data: {
firstName: 'Foo',
lastName: 'Bar',
fullName: 'Foo Bar'
},
watch: {
//newval和oldval不相等,即firstname发生了改变就会执行下面的回调函数中的所有操作
firstName: function (newval,oldval) {
this.fullName = newval + ' ' + this.lastName
},
//同上
lastName: function (newval,oldval) {
this.fullName = this.firstName + ' ' + newval
}
}
})
computed是计算属性,可以对数据进行获取和修改:
//一般用法,只有获取
var vm = new Vue({
el: '#demo',
data: {
firstName: 'Foo',
lastName: 'Bar'
},
computed: {
fullName: function () {
return this.firstName + ' ' + this.lastName
}
}
})
// 若要对数据进行修改
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]
}
}
}