[Vue]method與計算屬性computed、偵聽器watch與計算屬性computed的區別
阿新 • • 發佈:2019-05-16
相關 return compute 進行 names 變量 使用 bsp 一個數
一.方法method與計算屬性computed的區別
方法method:每當觸發重新渲染時,調用方法method將總會再次執行函數;
計算屬性computed:計算屬性computed是基於它們的響應式依賴進行緩存的,只在相關響應式依賴發生改變時它們才會重新求值;
二.偵聽器watch與計算屬性computed的區別
1.watch監聽的是一個變量(或者一個常量)
的變化,這個變量可能是一個單一的變化也可能是一個數組。computed可以監聽很多個變量,但是這個變量一定是vue實例裏面的。
2.
計算屬性computed:如果只是監聽數據的變動更好的做法是使用計算屬性而不是偵聽器watch;
偵聽器watch:當需要在數據變化時執行異步或開銷較大的操作時,偵聽器watch是最有用的(至於為什麽此時不能用計算屬性computed還沒有查到依據,有小夥伴知道的可以回復一下~);
另外:計算屬性computed的setter
計算屬性默認只有 getter ,不過在需要時你也可以提供一個 setter :
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] } } }
現在再運行 vm.fullName = ‘John Doe‘
時,setter 會被調用,vm.firstName
和 vm.lastName
也會相應地被更新。
[Vue]method與計算屬性computed、偵聽器watch與計算屬性computed的區別