vue2 中 computed 和 watch 的異同
一、computed 和 watch 都可以觀察頁面的資料變化。當處理頁面的資料變化時,我們有時候很容易濫用watch。 而通常更好的辦法是使用computed屬性,而不是命令是的watch回撥。 這裡我直接引用vue官網的例子來說明:
html:
我們要實現 第三個表單的值 是第一個和第二個的拼接,並且在前倆表單數值變化時,第三個表單數值也在變化
<div id="myDiv"> <input type="text" v-model="firstName"> <input type="text" v-model="lastName"> <input type="text" v-model="fullName"> </div>
- 1
- 2
- 3
- 4
- 5
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 } } })
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
js: 利用computed 來寫
new Vue({ el:"#myDiv", data:{ firstName:"Den", lastName:"wang", }, computed:{ fullName:function(){ return this.firstName + " " +this.lastName; } } })
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
很容易看出 computed 在實現上邊的效果時,是更簡單的。
二 、 詳解 comouted 計算屬性。 在vue的 模板內({{}})是可以寫一些簡單的js表示式的 ,很便利。但是如果在頁面中使用大量或是複雜的表示式去處理資料,對頁面的維護會有很大的影響。這個時候就需要用到computed 計算屬性來處理複雜的邏輯運算。
1.優點: 在資料未發生變化時,優先讀取快取。computed 計算屬性只有在相關的資料發生變化時才會改變要計算的屬性,當相關資料沒有變化是,它會讀取快取。而不必想 motheds方法 和 watch 方法是的每次都去執行函式。
2.setter 和 getter方法:(注意在vue中書寫時用set 和 get) setter 方法在設定值是觸發。 getter 方法在獲取值時觸發。
computed:{
fullName:{
//這裡用了es6書寫方法
set(){
alert("set");
},
get(){
alert("get");
return this.firstName + " " +this.lastName;
},
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
三 、watch 方法 雖然計算屬性在大多數情況下是非常適合的,但是在有些情況下我們需要自定義一個watcher,在資料變化時來執行非同步操作,這時watch是非常有用的。
--------------------- 本文來自 webxiaoma 的CSDN 部落格 ,全文地址請點選:https://blog.csdn.net/webxiaoma/article/details/72626439?utm_source=copy