先從一個例子分析
<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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/43664.html
標籤:Html/Css
上一篇:Hugo博客搭建
