模板內(nèi)的表達(dá)式非常便利,但是設(shè)計(jì)它們的初衷是用于簡(jiǎn)單運(yùn)算的。在模板中放入太多的邏輯會(huì)讓模板過重且難以維護(hù)。例如,有一個(gè)嵌套數(shù)組對(duì)象:
Vue.createApp({
data() {
return {
author: {
name: 'John Doe',
books: [
'Vue 2 - Advanced Guide',
'Vue 3 - Basic Guide',
'Vue 4 - The Mystery'
]
}
}
}
})
我們想根據(jù) author
是否已經(jīng)有一些書來顯示不同的消息
<div id="computed-basics">
<p>Has published books:</p>
<span>{{ author.books.length > 0 ? 'Yes' : 'No' }}</span>
</div>
此時(shí),模板不再是簡(jiǎn)單的和聲明性的。你必須先看一下它,然后才能意識(shí)到它執(zhí)行的計(jì)算取決于 author.books
。如果要在模板中多次包含此計(jì)算,則問題會(huì)變得更糟。
所以,對(duì)于任何包含響應(yīng)式數(shù)據(jù)的復(fù)雜邏輯,你都應(yīng)該使用計(jì)算屬性。
<div id="computed-basics">
<p>Has published books:</p>
<span>{{ publishedBooksMessage }}</span>
</div>
Vue.createApp({
data() {
return {
author: {
name: 'John Doe',
books: [
'Vue 2 - Advanced Guide',
'Vue 3 - Basic Guide',
'Vue 4 - The Mystery'
]
}
}
},
computed: {
// 計(jì)算屬性的 getter
publishedBooksMessage() {
// `this` points to the vm instance
return this.author.books.length > 0 ? 'Yes' : 'No'
}
}
}).mount('#computed-basics')
Result: 點(diǎn)擊此處實(shí)現(xiàn)
這里聲明了一個(gè)計(jì)算屬性 publishedBooksMessage
。
嘗試更改應(yīng)用程序 data
中 books
數(shù)組的值,你將看到 publishedBooksMessage
如何相應(yīng)地更改。
你可以像普通屬性一樣將數(shù)據(jù)綁定到模板中的計(jì)算屬性。Vue 知道 vm.publishedBookMessage
依賴于 vm.author.books
,因此當(dāng) vm.author.books
發(fā)生改變時(shí),所有依賴 vm.publishedBookMessage
綁定也會(huì)更新。而且最妙的是我們已經(jīng)聲明的方式創(chuàng)建了這個(gè)依賴關(guān)系:計(jì)算屬性的 getter 函數(shù)沒有副作用,這使得更易于測(cè)試和理解。
你可能已經(jīng)注意到我們可以通過在表達(dá)式中調(diào)用方法來達(dá)到同樣的效果:
<p>{{ calculateBooksMessage() }}</p>
// 在組件中
methods: {
calculateBooksMessage() {
return this.author.books.length > 0 ? 'Yes' : 'No'
}
}
我們可以將同一函數(shù)定義為一個(gè)方法而不是一個(gè)計(jì)算屬性。兩種方式的最終結(jié)果確實(shí)是完全相同的。然而,不同的是計(jì)算屬性是基于它們的反應(yīng)依賴關(guān)系緩存的。計(jì)算屬性只在相關(guān)響應(yīng)式依賴發(fā)生改變時(shí)它們才會(huì)重新求值。這就意味著只要 author.books
還沒有發(fā)生改變,多次訪問 publishedBookMessage
計(jì)算屬性會(huì)立即返回之前的計(jì)算結(jié)果,而不必再次執(zhí)行函數(shù)。
這也同樣意味著下面的計(jì)算屬性將不再更新,因?yàn)?Date.now () 不是響應(yīng)式依賴:
computed: {
now() {
return Date.now()
}
}
相比之下,每當(dāng)觸發(fā)重新渲染時(shí),調(diào)用方法將總會(huì)再次執(zhí)行函數(shù)。
我們?yōu)槭裁葱枰彺??假設(shè)我們有一個(gè)性能開銷比較大的計(jì)算屬性 list
,它需要遍歷一個(gè)巨大的數(shù)組并做大量的計(jì)算。然后我們可能有其他的計(jì)算屬性依賴于 list
。如果沒有緩存,我們將不可避免的多次執(zhí)行 list
的 getter!如果你不希望有緩存,請(qǐng)用 method
來替代。
計(jì)算屬性默認(rèn)只有 getter,不過在需要時(shí)你也可以提供一個(gè) setter:
// ...
computed: {
fullName: {
// getter
get() {
return this.firstName + ' ' + this.lastName
},
// setter
set(newValue) {
const names = newValue.split(' ')
this.firstName = names[0]
this.lastName = names[names.length - 1]
}
}
}
// ...
現(xiàn)在再運(yùn)行 vm.fullName = 'John Doe'
時(shí),setter 會(huì)被調(diào)用,vm.firstName
和 vm.lastName
也會(huì)相應(yīng)地被更新。
雖然計(jì)算屬性在大多數(shù)情況下更合適,但有時(shí)也需要一個(gè)自定義的偵聽器。這就是為什么 Vue 通過 watch
選項(xiàng)提供了一個(gè)更通用的方法,來響應(yīng)數(shù)據(jù)的變化。當(dāng)需要在數(shù)據(jù)變化時(shí)執(zhí)行異步或開銷較大的操作時(shí),這個(gè)方式是最有用的。
例如:
<div id="watch-example">
<p>
Ask a yes/no question:
<input v-model="question" />
</p>
<p>{{ answer }}</p>
</div>
<!-- 因?yàn)?AJAX 庫和通用工具的生態(tài)已經(jīng)相當(dāng)豐富,Vue 核心代碼沒有重復(fù) -->
<!-- 提供這些功能以保持精簡(jiǎn)。這也可以讓你自由選擇自己更熟悉的工具。 -->
<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js" rel="external nofollow" ></script>
<script>
const watchExampleVM = Vue.createApp({
data() {
return {
question: '',
answer: 'Questions usually contain a question mark. ;-)'
}
},
watch: {
// whenever question changes, this function will run
question(newQuestion, oldQuestion) {
if (newQuestion.indexOf('?') > -1) {
this.getAnswer()
}
}
},
methods: {
getAnswer() {
this.answer = 'Thinking...'
axios
.get('https://yesno.wtf/api')
.then(response => {
this.answer = response.data.answer
})
.catch(error => {
this.answer = 'Error! Could not reach the API. ' + error
})
}
}
}).mount('#watch-example')
</script>
結(jié)果: 點(diǎn)擊此處實(shí)現(xiàn)
在這個(gè)示例中,使用 watch
選項(xiàng)允許我們執(zhí)行異步操作 (訪問一個(gè) API),限制我們執(zhí)行該操作的頻率,并在我們得到最終結(jié)果前,設(shè)置中間狀態(tài)。這些都是計(jì)算屬性無法做到的。
除了 watch 選項(xiàng)之外,你還可以使用命令式的 vm.$watch API。
Vue 提供了一種更通用的方式來觀察和響應(yīng)當(dāng)前活動(dòng)的實(shí)例上的數(shù)據(jù)變動(dòng):偵聽屬性。當(dāng)你有一些數(shù)據(jù)需要隨著其它數(shù)據(jù)變動(dòng)而變動(dòng)時(shí),你很容易濫用 watch
——特別是如果你之前使用過 AngularJS。然而,通常更好的做法是使用計(jì)算屬性而不是命令式的 watch
回調(diào)。細(xì)想一下這個(gè)例子:
<div id="demo">{{ fullName }}</div>
const vm = Vue.createApp({
data() {
return {
firstName: 'Foo',
lastName: 'Bar',
fullName: 'Foo Bar'
}
},
watch: {
firstName(val) {
this.fullName = val + ' ' + this.lastName
},
lastName(val) {
this.fullName = this.firstName + ' ' + val
}
}
}).mount('#demo')
上面代碼是命令式且重復(fù)的。將它與計(jì)算屬性的版本進(jìn)行比較:
const vm = Vue.createApp({
data() {
return {
firstName: 'Foo',
lastName: 'Bar'
}
},
computed: {
fullName() {
return this.firstName + ' ' + this.lastName
}
}
}).mount('#demo')
好得多了,不是嗎?
更多建議: