Vue 3.0 計算屬性和偵聽器

2021-07-16 11:28 更新

#計算屬性

模板內(nèi)的表達式非常便利,但是設計它們的初衷是用于簡單運算的。在模板中放入太多的邏輯會讓模板過重且難以維護。例如,有一個嵌套數(shù)組對象:

  1. Vue.createApp({
  2. data() {
  3. return {
  4. author: {
  5. name: 'John Doe',
  6. books: [
  7. 'Vue 2 - Advanced Guide',
  8. 'Vue 3 - Basic Guide',
  9. 'Vue 4 - The Mystery'
  10. ]
  11. }
  12. }
  13. }
  14. })

我們想根據(jù) author 是否已經(jīng)有一些書來顯示不同的消息

  1. <div id="computed-basics">
  2. <p>Has published books:</p>
  3. <span>{{ author.books.length > 0 ? 'Yes' : 'No' }}</span>
  4. </div>

此時,模板不再是簡單的和聲明性的。你必須先看一下它,然后才能意識到它執(zhí)行的計算取決于 author.books。如果要在模板中多次包含此計算,則問題會變得更糟。

所以,對于任何包含響應式數(shù)據(jù)的復雜邏輯,你都應該使用計算屬性。

#基本例子

  1. <div id="computed-basics">
  2. <p>Has published books:</p>
  3. <span>{{ publishedBooksMessage }}</span>
  4. </div>

  1. Vue.createApp({
  2. data() {
  3. return {
  4. author: {
  5. name: 'John Doe',
  6. books: [
  7. 'Vue 2 - Advanced Guide',
  8. 'Vue 3 - Basic Guide',
  9. 'Vue 4 - The Mystery'
  10. ]
  11. }
  12. }
  13. },
  14. computed: {
  15. // 計算屬性的 getter
  16. publishedBooksMessage() {
  17. // `this` points to the vm instance
  18. return this.author.books.length > 0 ? 'Yes' : 'No'
  19. }
  20. }
  21. }).mount('#computed-basics')

Result: 點擊此處實現(xiàn)

這里聲明了一個計算屬性 publishedBooksMessage。

嘗試更改應用程序 databooks 數(shù)組的值,你將看到 publishedBooksMessage 如何相應地更改。

你可以像普通屬性一樣將數(shù)據(jù)綁定到模板中的計算屬性。Vue 知道 vm.publishedBookMessage 依賴于 vm.author.books,因此當 vm.author.books 發(fā)生改變時,所有依賴 vm.publishedBookMessage 綁定也會更新。而且最妙的是我們已經(jīng)聲明的方式創(chuàng)建了這個依賴關系:計算屬性的 getter 函數(shù)沒有副作用,這使得更易于測試和理解。

#計算屬性緩存 vs 方法

你可能已經(jīng)注意到我們可以通過在表達式中調(diào)用方法來達到同樣的效果:

  1. <p>{{ calculateBooksMessage() }}</p>

  1. // 在組件中
  2. methods: {
  3. calculateBooksMessage() {
  4. return this.author.books.length > 0 ? 'Yes' : 'No'
  5. }
  6. }

我們可以將同一函數(shù)定義為一個方法而不是一個計算屬性。兩種方式的最終結(jié)果確實是完全相同的。然而,不同的是計算屬性是基于它們的反應依賴關系緩存的。計算屬性只在相關響應式依賴發(fā)生改變時它們才會重新求值。這就意味著只要 author.books 還沒有發(fā)生改變,多次訪問 publishedBookMessage 計算屬性會立即返回之前的計算結(jié)果,而不必再次執(zhí)行函數(shù)。

這也同樣意味著下面的計算屬性將不再更新,因為 Date.now () 不是響應式依賴:

  1. computed: {
  2. now() {
  3. return Date.now()
  4. }
  5. }

相比之下,每當觸發(fā)重新渲染時,調(diào)用方法將總會再次執(zhí)行函數(shù)。

我們?yōu)槭裁葱枰彺??假設我們有一個性能開銷比較大的計算屬性 list,它需要遍歷一個巨大的數(shù)組并做大量的計算。然后我們可能有其他的計算屬性依賴于 list。如果沒有緩存,我們將不可避免的多次執(zhí)行 list 的 getter!如果你不希望有緩存,請用 method 來替代。

#計算屬性的 Setter

計算屬性默認只有 getter,不過在需要時你也可以提供一個 setter:

  1. // ...
  2. computed: {
  3. fullName: {
  4. // getter
  5. get() {
  6. return this.firstName + ' ' + this.lastName
  7. },
  8. // setter
  9. set(newValue) {
  10. const names = newValue.split(' ')
  11. this.firstName = names[0]
  12. this.lastName = names[names.length - 1]
  13. }
  14. }
  15. }
  16. // ...

現(xiàn)在再運行 vm.fullName = 'John Doe' 時,setter 會被調(diào)用,vm.firstNamevm.lastName 也會相應地被更新。

#偵聽器

雖然計算屬性在大多數(shù)情況下更合適,但有時也需要一個自定義的偵聽器。這就是為什么 Vue 通過 watch 選項提供了一個更通用的方法,來響應數(shù)據(jù)的變化。當需要在數(shù)據(jù)變化時執(zhí)行異步或開銷較大的操作時,這個方式是最有用的。

例如:

  1. <div id="watch-example">
  2. <p>
  3. Ask a yes/no question:
  4. <input v-model="question" />
  5. </p>
  6. <p>{{ answer }}</p>
  7. </div>

  1. <!-- 因為 AJAX 庫和通用工具的生態(tài)已經(jīng)相當豐富,Vue 核心代碼沒有重復 -->
  2. <!-- 提供這些功能以保持精簡。這也可以讓你自由選擇自己更熟悉的工具。 -->
  3. <script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js" rel="external nofollow" ></script>
  4. <script>
  5. const watchExampleVM = Vue.createApp({
  6. data() {
  7. return {
  8. question: '',
  9. answer: 'Questions usually contain a question mark. ;-)'
  10. }
  11. },
  12. watch: {
  13. // whenever question changes, this function will run
  14. question(newQuestion, oldQuestion) {
  15. if (newQuestion.indexOf('?') > -1) {
  16. this.getAnswer()
  17. }
  18. }
  19. },
  20. methods: {
  21. getAnswer() {
  22. this.answer = 'Thinking...'
  23. axios
  24. .get('https://yesno.wtf/api')
  25. .then(response => {
  26. this.answer = response.data.answer
  27. })
  28. .catch(error => {
  29. this.answer = 'Error! Could not reach the API. ' + error
  30. })
  31. }
  32. }
  33. }).mount('#watch-example')
  34. </script>

結(jié)果: 點擊此處實現(xiàn)

在這個示例中,使用 watch 選項允許我們執(zhí)行異步操作 (訪問一個 API),限制我們執(zhí)行該操作的頻率,并在我們得到最終結(jié)果前,設置中間狀態(tài)。這些都是計算屬性無法做到的。

除了 watch 選項之外,你還可以使用命令式的 vm.$watch API。

#計算屬性 vs 偵聽器

Vue 提供了一種更通用的方式來觀察和響應當前活動的實例上的數(shù)據(jù)變動:偵聽屬性。當你有一些數(shù)據(jù)需要隨著其它數(shù)據(jù)變動而變動時,你很容易濫用 watch——特別是如果你之前使用過 AngularJS。然而,通常更好的做法是使用計算屬性而不是命令式的 watch 回調(diào)。細想一下這個例子:

  1. <div id="demo">{{ fullName }}</div>

  1. const vm = Vue.createApp({
  2. data() {
  3. return {
  4. firstName: 'Foo',
  5. lastName: 'Bar',
  6. fullName: 'Foo Bar'
  7. }
  8. },
  9. watch: {
  10. firstName(val) {
  11. this.fullName = val + ' ' + this.lastName
  12. },
  13. lastName(val) {
  14. this.fullName = this.firstName + ' ' + val
  15. }
  16. }
  17. }).mount('#demo')

上面代碼是命令式且重復的。將它與計算屬性的版本進行比較:

  1. const vm = Vue.createApp({
  2. data() {
  3. return {
  4. firstName: 'Foo',
  5. lastName: 'Bar'
  6. }
  7. },
  8. computed: {
  9. fullName() {
  10. return this.firstName + ' ' + this.lastName
  11. }
  12. }
  13. }).mount('#demo')

好得多了,不是嗎?

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號