Vue中data對象 vs 方法 vs 計算屬性比較
先從一個例子分析
source array:{{numbers}}sorted array:{{sortArray()}}3 in array index : {{findIndex(3)}}totalNumbers : {{totalNumbers}}修改數組export default {
data() { return { numbers: [1, 5, 3, 9, 2, 4, 8] };
},
computed: {
totalNumbers() {
console.log("compute total"); return this.numbers.reduce((total, val) => total + val);
}
},
methods: {
sortArray() { return this.numbers.slice(0).sort((a, b) => a - b);
},
findIndex(value) {
console.log("find index"); return this.numbers.findIndex(m => m === value);
},
changeArray() { for (let i = 0; i this.numbers.length; i++) { this.$set(this.numbers, i, Math.floor(Math.random() * 100));
}
}
}
};" _ue_custom_node_="true">

運作效果
1. 首先定義一組數組(資料)
2. 定義計算屬性,計算數組總和(計算屬性)
3. 定義3個方法,排序數組,查找指定值下标,修改數組(方法)
資料
data對象最适合純粹的資料:如果想将資料放在某處,然後在模闆、方法或者計算屬性中使用
計算屬性
計算屬性适用于執行更加複雜的表達式,這些表達式往往太長或者需要頻繁地重複使用
計算屬性會有緩存,依賴的資料沒有變化,會直接從緩存裡取出,這個可以列印console.log,計算屬性可以驗證。是以計算屬性适合用于密集cpu計算。
計算屬性可以設定讀寫
total:{
get(){
....
}
set(){
...
}
}
方法
如果希望為模闆添加函數功能時,最好使用方法,通常是傳遞參數,根據參數得到不同結果。
可讀 | 可寫 | 接受參數 | 需要運算 | 緩存 | |
---|---|---|---|---|---|
data | 是 | 不能 | 否 | ||
能 | |||||