先從一個例子分析
<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()">修改數(shù)組</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>
運行效果
- 首先定義一組數(shù)組(數(shù)據(jù))
- 定義計算屬性弓乙,計算數(shù)組總和(計算屬性)
- 定義3個方法,排序數(shù)組冯遂,查找指定值下標(biāo)拟枚,修改數(shù)組(方法)
數(shù)據(jù)
data對象最適合純粹的數(shù)據(jù):如果想將數(shù)據(jù)放在某處颂郎,然后在模板吼渡、方法或者計算屬性中使用
計算屬性
計算屬性適用于執(zhí)行更加復(fù)雜的表達(dá)式,這些表達(dá)式往往太長或者需要頻繁地重復(fù)使用
計算屬性會有緩存乓序,依賴的數(shù)據(jù)沒有變化寺酪,會直接從緩存里取出,這個可以打印console.log替劈,計算屬性可以驗證寄雀。所以計算屬性適合用于密集cpu計算。
計算屬性可以設(shè)置讀寫
total:{
get(){
....
}
set(){
...
}
}
方法
希望為模板添加函數(shù)功能時陨献,最好使用方法盒犹,通常是傳遞參數(shù),根據(jù)參數(shù)得到不同結(jié)果眨业。
data對象 vs 方法 vs 計算屬性
? | 可讀 | 可寫 | 接受參數(shù) | 需要運算 | 緩存 |
---|---|---|---|---|---|
data | 是 | 是 | 不能 | 否 | 否 |
方法 | 是 | 否 | 能 | 是 | 否 |
計算屬性 | 是 | 是 | 否 | 是 | 是 |