1、computed 和 watch 均可以觀察頁面的數據變化。當處理頁面的數據變化時,咱們有時候很容易濫用watch。 而一般更好的辦法是使用computed屬性,而不是命令是的watch回調。
這裏我直接引用vue官網的例子來講明:html
html:vue
咱們要實現 第三個表單的值 是第一個和第二個的拼接,而且在前倆表單數值變化時,第三個表單數值也在變化es6
<div id="myDiv"> <input type="text" v-model="firstName"> <input type="text" v-model="lastName"> <input type="text" v-model="fullName"> </div>
js: 用watch方法來實現緩存
new Vue({ el: '#myDiv', 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 } } })
js: 利用computed 來寫異步
new Vue({ el:"#myDiv", data:{ firstName:"Den", lastName:"wang", }, computed:{ fullName:function(){ return this.firstName + " " +this.lastName; } } })
很容易看出 computed 在實現上邊的效果時,是更簡單的。函數
二 、 詳解 comouted 計算屬性。
在vue的 模板內({{}})是能夠寫一些簡單的js表達式的 ,很便利。可是若是在頁面中使用大量或是複雜的表達式去處理數據,對頁面的維護會有很大的影響。這個時候就須要用到computed 計算屬性來處理複雜的邏輯運算。this
1.優勢:
在數據未發生變化時,優先讀取緩存。computed 計算屬性只有在相關的數據發生變化時纔會改變要計算的屬性,當相關數據沒有變化是,它會讀取緩存。而沒必要想 motheds方法 和 watch 方法是的每次都去執行函數。spa
2.setter 和 getter方法:(注意在vue中書寫時用set 和 get)
setter 方法在設置值是觸發。
getter 方法在獲取值時觸發。code
computed:{ fullName:{ //這裏用了es6書寫方法 set(){ alert("set"); }, get(){ alert("get"); return this.firstName + " " +this.lastName; }, } }
三 、watch 方法
雖然計算屬性在大多數狀況下是很是適合的,可是在有些狀況下咱們須要自定義一個watcher,在數據變化時來執行異步操做,這時watch是很是有用的。htm