在模板中綁定表達式是非常便利的,但是它們實際上只用于簡單的操作。在模板中放入太多的邏輯會讓模板過重且難以維護。例如:
<div id="example"> {{ message.split('').reverse().join('') }} </div>
在這種情況下,模板不再簡單和清晰。在實現反向顯示 message
之前,你應該確認它。這個問題在你不止一次反向顯示 message 的時候變得更加糟糕。
這就是為什么任何復雜邏輯,你都應當使用計算屬性。
基礎例子
<div id="example"> <p>Original message: "{{ message }}"</p> <p>Computed reversed message: "{{ reversedMessage }}"</p> </div>
var vm = new Vue({
el: '#example',
data: {
message: 'Hello'
},
computed: {
// a computed getter
reversedMessage: function () {
// `this` points to the vm instance
return this.message.split('').reverse().join('')
}
}
})
結果:
Original message: "Hello"
Computed reversed message: "olleH"
這里我們聲明了一個計算屬性 reversedMessage
。我們提供的函數將用作屬性 vm.reversedMessage
的 getter 。
console.log(vm.reversedMessage) // -> 'olleH' vm.message = 'Goodbye' console.log(vm.reversedMessage) // -> 'eybdooG'
你可以打開瀏覽器的控制臺,修改 vm 。 vm.reversedMessage
的值始終取決于 vm.message
的值。
你可以像綁定普通屬性一樣在模板中綁定計算屬性。 Vue 知道 vm.reversedMessage
依賴于 vm.message
,因此當 vm.message
發生改變時,依賴于 vm.reversedMessage
的綁定也會更新。而且最妙的是我們是聲明式地創建這種依賴關系:計算屬性的 getter 是干凈無副作用的,因此也是易于測試和理解的。
計算緩存 vs methods
你可能已經注意到我們可以通過調用表達式中的method來達到同樣的效果:
<p>Reversed message: "{{ reverseMessage() }}"</p>
// in component methods: { reverseMessage: function () { return this.message.split('').reverse().join('') } }
不經過計算屬性,我們可以在 method 中定義一個相同的函數來替代它。對于最終的結果,兩種方式確實是相同的。然而,不同的是計算屬性是基于它的依賴緩存。計算屬性只有在它的相關依賴發生改變時才會重新取值。這就意味著只要 message
沒有發生改變,多次訪問 reversedMessage
計算屬性會立即返回之前的計算結果,而不必再次執行函數。
這也同樣意味著如下計算屬性將不會更新,因為 Date.now()
不是響應式依賴:
computed: { now: function () { return Date.now() } }
相比而言,每當重新渲染的時候,method 調用總會執行函數。
我們為什么需要緩存?假設我們有一個重要的計算屬性 A ,這個計算屬性需要一個巨大的數組遍歷和做大量的計算。然后我們可能有其他的計算屬性依賴于 A 。如果沒有緩存,我們將不可避免的多次執行 A 的 getter !如果你不希望有緩存,請用 method 替代。
計算屬性 vs Watched Property
Vue.js 提供了一個方法 $watch
,它用于觀察 Vue 實例上的數據變動。當一些數據需要根據其它數據變化時, $watch
很誘人 —— 特別是如果你來自 AngularJS 。不過,通常更好的辦法是使用計算屬性而不是一個命令式的 $watch
回調。思考下面例子:
<div id="demo">{{ fullName }}</div>
var vm = new Vue({ el: '#demo', data: { firstName: 'Foo', lastName: 'Bar', fullName: 'Foo Bar' }, watch: { firstName: function (val) { this.fullName = val + ' ' + this.lastName }, lastName: function (val) { this.fullName = this.firstName + ' ' + val } } })
上面代碼是命令式的和重復的。跟計算屬性對比:
var vm = new Vue({ el: '#demo', data: { firstName: 'Foo', lastName: 'Bar' }, computed: { fullName: function () { return this.firstName + ' ' + this.lastName } } })
這樣更好,不是嗎?
計算setter
計算屬性默認只有 getter ,不過在需要時你也可以提供一個 setter :
// ... computed: { fullName: { // getter get: function () { return this.firstName + ' ' + this.lastName }, // setter set: function (newValue) { var names = newValue.split(' ') this.firstName = names[0] this.lastName = names[names.length - 1] } } } // ...
現在在運行 vm.fullName = 'John Doe'
時, setter 會被調用, vm.firstName
和 vm.lastName
也會被對應更新。
觀察 Watchers
雖然計算屬性在大多數情況下更合適,但有時也需要一個自定義的 watcher 。這是為什么 Vue 提供一個更通用的方法通過 watch
選項,來響應數據的變化。當你想要在數據變化響應時,執行異步操作或開銷較大的操作,這是很有用的。
例如:
<div id="watch-example">
<p>
Ask a yes/no question:
<input v-model="question">
</p>
<p>{{ answer }}</p>
</div>
<!-- Since there is already a rich ecosystem of ajax libraries --> <!-- and collections of general-purpose utility methods, Vue core --> <!-- is able to remain small by not reinventing them. This also --> <!-- gives you the freedom to just use what you're familiar with. --> <script src="https://unpkg.com/axios@0.12.0/dist/axios.min.js"></script> <script src="https://unpkg.com/lodash@4.13.1/lodash.min.js"></script> <script> var watchExampleVM = new Vue({ el: '#watch-example', data: { question: '', answer: 'I cannot give you an answer until you ask a question!' }, watch: { // 如果 question 發生改變,這個函數就會運行 question: function (newQuestion) { this.answer = 'Waiting for you to stop typing...' this.getAnswer() } }, methods: { // _.debounce 是一個通過 lodash 限制操作頻率的函數。 // 在這個例子中,我們希望限制訪問yesno.wtf/api的頻率 // ajax請求直到用戶輸入完畢才會發出 // 學習更多關于 _.debounce function (and its cousin // _.throttle), 參考: https://lodash.com/docs#debounce getAnswer: _.debounce( function () { var vm = this if (this.question.indexOf('?') === -1) { vm.answer = 'Questions usually contain a question mark. ;-)' return } vm.answer = 'Thinking...' axios.get('https://yesno.wtf/api') .then(function (response) { vm.answer = _.capitalize(response.data.answer) }) .catch(function (error) { vm.answer = 'Error! Could not reach the API. ' + error }) }, // 這是我們為用戶停止輸入等待的毫秒數 500 ) } }) </script>

在這個示例中,使用
watch
選項允許我們執行異步操作(訪問一個 API),限制我們執行該操作的頻率,并在我們得到最終結果前,設置中間狀態。這是計算屬性無法做到的。
除了 watch
選項之外,您還可以使用 vm.$watch API 命令。
文章列表