概述:
?computed的計(jì)算屬性有緩存機(jī)制,只有當(dāng)其依賴的響應(yīng)式數(shù)據(jù)發(fā)生變化時(shí)才會(huì)清空緩存重新計(jì)算結(jié)果,其緩存機(jī)制本質(zhì)是通過一個(gè)dirty屬性控制的,只有dirty為true時(shí)才會(huì)重新計(jì)算結(jié)果替換緩存。dirty只有當(dāng)其響應(yīng)式數(shù)據(jù)發(fā)送變化時(shí)才會(huì)設(shè)置為true,重新計(jì)算后會(huì)再次被設(shè)置為false
為什么說計(jì)算屬性有緩存功能呢,
? ? ? 假設(shè)一個(gè)template中 {{ computedVal }} // computedVal定義在計(jì)算屬性中,是a+b
? ? 另一個(gè)是? {{ a+b }}的 moustache 語法中是一個(gè)計(jì)算屬性,
? ? 那么每次render的時(shí)候都會(huì)計(jì)算a+b,而computedVal不會(huì)計(jì)算,可以直接從computedVal中拿值(對(duì)應(yīng)的一個(gè)watcher的value)
<template>
? ? ? <div>
? ? ? ? ? <button @click="changeValue">更新Value</button>
? ? ? ? ? <button @click="getComputedValue">打印computedValue</button>
? ? ?</div>
</template>
<script>
? ? export default {
? ? ? ? ? ? ? data(){
? ? ? ? ? ? ? ? ? ? ?return {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? value: 1
? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? },
? ? ? ?computed: {
? ? ? ? ? ? ? computedValue(){
? ? ? ? ? ? ? ? ? ? ? ?return this.value + '--' + Math.random()
? ? ? ? ? ? ? }
? ? ? ? },
? ? ? methods: {
? ? ? ? ? ? ? changeValue(){
? ? ? ? ? ? ? ? ? ? ? ? this.value++;
? ? ? ? ? ? },
? ? ? ? ? getComputedValue(){
? ? ? ? ? ? ? ? ? console.log(this.computedValue);
? ? ? ? ? ?}
? ? ?}
}
</script>
結(jié)果
? ? ? 點(diǎn)擊第二個(gè)按鈕,多次獲取computedValue的值時(shí),返回的值都是相同的,Math.random()不會(huì)重新獲取。體現(xiàn)了computed的緩存特性。只有當(dāng)點(diǎn)擊了第一個(gè)按鈕,修改了computedValue依賴的響應(yīng)式數(shù)據(jù)后,才會(huì)更新computedValue的緩存