在實際項目開發(fā)中,computed計算屬性使用場景及其豐富悬荣。下面是個人的一些使用心得
1.當(dāng)一個對象為計算屬性時菠秒,不需要在data中定義。
2.當(dāng)一個對象為計算屬性時氯迂。在其方法中践叠,使用的變量發(fā)生改變了,就會觸發(fā)這個計算函數(shù)
<template>
<div>
<el-button @click="testFunc">點我</el-button>
<div>{{testCom}}</div>
</div>
</template>
<script>
export default {
name: 'testComputed',
computed: {
testCom () {
// 可以嘗試寫下代碼看下computed執(zhí)行了幾次嚼蚀?執(zhí)行1測禁灼。因為首次加載引用了testCom。但是計算屬性中驰坊,引用的testFunc方法中的age是基本數(shù)據(jù)類型匾二。值是相等的哮独∪剑可以視為沒改變。因此testCom不會再次觸發(fā)皮璧。
console.log('computed', this.testFunc())
return this.testFunc()
}
},
data () {
return {
age: 1
}
},
methods: {
testFunc () {
this.age = 10
return this.age
}
}
}
</script>
<style scoped>
</style>
在看下面代碼
<template>
<div>
<el-button @click="testFunc">點我</el-button>
<div>{{testCom}}</div>
</div>
</template>
<script>
export default {
name: 'testComputed',
computed: {
testCom () {
console.log('computed', this.testFunc())
return this.testFunc()
}
},
data () {
return {
age: []//只是此處改變了
}
},
methods: {
testFunc () {
this.age = [10]//只是此處改變了
return this.age
}
}
}
</script>
<style scoped>
</style>
這樣舟扎,點擊按鈕,就是一直觸發(fā)computed屬性悴务。因為computed中testCom所依賴的testFunc方法中睹限,age改變了譬猫。。雖然都是數(shù)組羡疗,但是引用數(shù)據(jù)類型染服。每次賦值都會視為新對象∵逗蓿可以自行使用
console.log('比較',[10]===[10])
進行輸出查看柳刮。
總結(jié)來說: