Vue基礎:計算屬性和偵聽器

計算屬性

1、簡單示例

<div id="app">
  <p>最初信息:{{message}}</p>
  <p>computed後信息:{{reversedMessage}}</p>
 </div>
 <script>
  var app1=new Vue({
   el:'#app',
   data:{
    message:'hello'
   },
   computed:{
    reversedMessage:function(){
     return this.message.split('').reverse().join('');
    }
   }
  })
 </script>

在這裏插入圖片描述
2、計算屬性緩存vs方法

// 在組件中
methods: {
  reversedMessage: function () {
    return this.message.split('').reverse().join('')
  }
}

將同一函數定義爲一個方法而不是一個計算屬性。兩種方式的最終結果確實是完全相同的。然而,不同的是計算屬性是基於它們的響應式依賴進行緩存的。只在相關響應式依賴發生改變時它們纔會重新求值。這就意味着只要 message 還沒有發生改變,多次訪問 reversedMessage 計算屬性會立即返回之前的計算結果,而不必再次執行函數。

爲什麼需要緩存?假設有一個性能開銷比較大的計算屬性 A,它需要遍歷一個巨大的數組並做大量的計算。然後我們可能有其他的計算屬性依賴於 A 。如果沒有緩存,那麼將不可避免的多次執行 A 的 getter!如果不希望有緩存,請用方法來替代。

3、計算屬性vs偵聽屬性

Vue 提供了一種更通用的方式來觀察和響應 Vue 實例上的數據變動:偵聽屬性。當你有一些數據需要隨着其它數據變動而變動時,你很容易濫用 watch。

(1)watch回調

<div id="demo">{{ fullName }}</div>
 <script>
  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
      }
    }
  })
 </script>

運行結果:Foo Bar
(2)計算屬性

<div id="demo">{{ fullName }}</div>
 <script>
  var vm = new Vue({
    el: '#demo',
    data: {
      firstName: 'Foo',
      lastName: 'Bar'
    },
    computed: {
      fullName: function () {
        return this.firstName + ' ' + this.lastName
      }
    }
  })
 </script>

運行結果:Foo Bar

4、計算屬性的setter

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

<div id="demo">{{ fullName }}</div>
 <script>
  var vm = new Vue({
    el: '#demo',
    data: {
      firstName: 'Foo',
      lastName: 'Bar'
    },
   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]
       }
     }
   }
  })
 </script>

運行結果:Foo Bar

偵聽器

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

示例

<div id="watch-example">
   <p>
     Ask a yes/no question:
     <input v-model="question">
   </p>
   <p>{{ answer }}</p>
 </div>
 <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script>
 <script src="https://cdn.jsdelivr.net/npm/[email protected]/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, oldQuestion) {
        this.answer = 'Waiting for you to stop typing...'
        this.debouncedGetAnswer()
      }
    },
    created: function () {
        this.debouncedGetAnswer = _.debounce(this.getAnswer, 500)
    },
    methods: {
      getAnswer: function () {
        if (this.question.indexOf('?') === -1) {
          this.answer = 'Questions usually contain a question mark. ;-)'
          return
        }
        this.answer = 'Thinking...'
        var vm = this
        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
          })
      }
    }
  })
 </script>

在這裏插入圖片描述

發佈了132 篇原創文章 · 獲贊 26 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章