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:app
可是:函數
// 將「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) } })