先從一個例子分析
<template>
<div>
<p>source array:{{numbers}}</p>
<p>sorted array:{{sortArray()}}</p>
<p>3 in array index : {{findIndex(3)}}</p>
<p>totalNumbers : {{totalNumbers}}</p>
<button @click="changeArray()">修改數組</button>
</div>
</template>
<script>
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));
}
}
}
};
</script>

運行效果
1. 首先定義一組數組(數據)
2. 定義計算屬性,計算數組總和(計算屬性)
3. 定義3個方法,排序數組,查找指定值下標,修改數組(方法)
數據
data對象最適合純粹的數據:如果想將數據放在某處,然后在模板、方法或者計算屬性中使用
計算屬性
計算屬性適用於執行更加復雜的表達式,這些表達式往往太長或者需要頻繁地重復使用
計算屬性會有緩存,依賴的數據沒有變化,會直接從緩存里取出,這個可以打印console.log,計算屬性可以驗證。所以計算屬性適合用於密集cpu計算。
計算屬性可以設置讀寫
total:{
get(){
....
}
set(){
...
}
}
方法
如果希望為模板添加函數功能時,最好使用方法,通常是傳遞參數,根據參數得到不同結果。
data對象 vs 方法 vs 計算屬性
| 可讀 | 可寫 | 接受參數 | 需要運算 | 緩存 | |
|---|---|---|---|---|---|
| data | 是 | 是 | 不能 | 否 | 否 |
| 方法 | 是 | 否 | 能 | 是 | 否 |
| 計算屬性 | 是 | 是 | 否 | 是 | 是 |
轉發請標明出處:https://www.cnblogs.com/WilsonPan/p/12755476.html
