computed:{ fullName: function () { return this.firstName + lastName } }
watch: { firstName: function (val) { this.fullName = val + this.lastName } }
var vm = new Vue({ el: ‘#app‘, /* data选项中的数据: 1.haiZeiTuan_Name --> 海贼团名称 2.船员的名称 = 海贼团名称(草帽海贼团) + 船员名称(例如索隆) 这些数据里存在这种关系: (多个)船员名称数据 --> 依赖于 --> (1个)海贼团名称数据 一个数据变化 ---> 多个数据全部变化 */ data: { haiZeiTuan_Name: ‘草帽海贼团‘, suoLong: ‘草帽海贼团索隆‘, naMei: ‘草帽海贼团娜美‘, xiangJiShi: ‘草帽海贼团香吉士‘ }, /* 在watch中,一旦haiZeiTuan_Name(海贼团名称)发生改变 data选项中的船员名称全部会自动改变 (suoLong,naMei,xiangJiShi) 并把它们打印出来 */ watch: { haiZeiTuan_Name: function (newName) { this.suoLong = newName + ‘索隆‘ this.naMei = newName + ‘娜美‘ this.xiangJiShi = newName + ‘香吉士‘ console.log(this.suoLong) console.log(this.naMei) console.log(this.xiangJiShi) } } }) // 更改watch选项中监控的主数据 vm.haiZeiTuan_Name = ‘橡胶海贼团‘
// 更改watch选项中监控的主数据 vm.haiZeiTuan_Name = ‘肉肉海贼团‘
demo:
var vm = new Vue({ el: ‘#app‘, /* data选项中的数据:firstName,secName,thirdName computed监控的数据:lufei_Name 两者关系: lufei_Name = firstName + secName + thirdName 所以等式右边三个数据任一改变,都会直接修改 lufei_Name */ data: { // 路飞的全名:蒙奇·D·路飞 firstName: ‘蒙奇‘, secName: ‘D‘, thirdName: ‘路飞‘ }, computed: { luFei_Name: function () { return this.firstName + this.secName + this.thirdName } } }) // 将“路飞”改为“海军王” vm.thirdName = ‘海军王‘ // 打印路飞的全名 console.log(vm.luFei_Name)
demo:
但是:
// 将“D”改为“H” vm.secName = ‘H‘ // 打印路飞的全名 console.log(vm.luFei_Name)
new Vue({ el: ‘#app‘, template: ‘<div id="app"><p>{{ say() }}</p></div>‘, methods: { say: function () { return ‘我要成为海贼王‘ } } })
new Vue({ el: ‘#app‘, // 设置两个button,点击分别调用getMethodsDate,getComputedDate方法 template: ‘<div id="app"><button @click="getMethodsDate">methods</button><button @click="getComputedDate">computed</button></div>‘, methods: { getMethodsDate: function () { alert(new Date()) }, // 返回computed选项中设置的计算属性——computedDate getComputedDate: function () { alert(this.computedDate) } }, computed: { computedDate: function () { return new Date() } }
new Vue({ el: ‘#app‘, data: { fullName: ‘彭湖湾‘, firstName: ‘彭‘, secName: ‘湖‘, thirdName: ‘湾‘ }, // watch中的代码显然是同类型,重复的,它并不简洁,也不优雅 watch: { firstName: function (newValue) { this.fullName = newValue + this.secName + this.thirdName console.log(this.fullName) }, secName: function (newValue) { this.fullName = this.firstName + newValue + this.thirdName console.log(this.fullName) }, thirdName: function (newValue) { this.fullName = this.firstName + this.secName + newValue console.log(this.fullName) } } })
new Vue({ el: ‘#app‘, data: { fullName: ‘彭湖湾‘, firstName: ‘彭‘, secName: ‘湖‘, thirdName: ‘湾‘ }, // 对watch中的代码进行重构,实现同样效果 computed: function () { this.fullName = this.firstName + this.secName + this.thirdName console.log(this.fullName) } })
【Vue】Vue的依赖追踪系统 ——搞懂methods watch和compute
原文:http://www.cnblogs.com/penghuwan/p/7194133.html