vue中computed與watch的異同

一、computed 和 watch

  都可以觀察頁面的數據變化。當處理頁面的數據變化時,我們有時候很容易濫用watch。 而通常更好的辦法是使用computed屬性,而不是命令是的watch回調。

/*html:

    我們要實現 第三個表單的值 是第一個和第二個的拼接,並且在前倆表單數值變化時,第三個表單數值也在變化
    */

<div id="myDiv">
    <input type="text" v-model="firstName">
    <input type="text" v-model="lastName">
    <input type="text" v-model="fullName">
</div>

<!--js: 用watch方法來實現-->
//將需要watch的屬性定義在watch中,當屬性變化氏就會動態的執行watch中的操作,並動態的可以更新到dom中 
 new Vue({
  el: '#myDiv',
  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
    }
  }
})

<!--js: 利用computed 來寫-->
    //計算屬性是基於它們的依賴進行緩存的。計算屬性只有在它的相關依賴發生改變時纔會重新求值。
    //這就意味着只要 message 還沒有發生改變,多次訪問 reversedMessage 計算屬性會立即返回之前的計算結果,而不必再次執行函數。
  new Vue({
       el:"#myDiv",
            data:{
                firstName:"Den",
                lastName:"wang",

            },
            computed:{
                fullName:function(){
                    return  this.firstName  + " " +this.lastName;
                }
            }
   })

  很容易看出 computed 在實現上邊的效果時,是更簡單的。

二 、 詳解 comouted 計算屬性。

  在vue的 模板內({{}})是可以寫一些簡單的js表達式的 ,很便利。但是如果在頁面中使用大量或是複雜的表達式去處理數據,對頁面的維護會有很大的影響。這個時候就需要用到computed 計算屬性來處理複雜的邏輯運算。
   1.優點: 在數據未發生變化時,優先讀取緩存。computed 計算屬性只有在相關的數據發生變化時纔會改變要計算的屬性,當相關數據沒有變化是,它會讀取緩存。而不必想 motheds方法 和 watch 方法是的每次都去執行函數。
  2.setter 和 getter方法:(注意在vue中書寫時用set 和 get) setter 方法在設置值是觸發。 getter 方法在獲取值時觸發。

        computed:{
             fullName:{
                 //這裏用了es6書寫方法 
                set(){ alert("set"); }, 
                get(){ alert("get"); 
            return this.firstName + " " +this.lastName; },
                }
             }

三 、watch 方法

   雖然計算屬性在大多數情況下是非常適合的,但是在有些情況下我們需要自定義一個watcher,當需要在數據變化時執行異步或開銷較大的操作時,這時watch是非常有用的。
例如:

     <div id="watch-example">
    <p>
        Ask a yes/no question:
        <input v-model="question">
    </p>
    <p>{{ answer }}</p>
</div>
<!-- 因爲 AJAX 庫和通用工具的生態已經相當豐富,Vue 核心代碼沒有重複 -->
<!-- 提供這些功能以保持精簡。這也可以讓你自由選擇自己更熟悉的工具。 -->
<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) {
                this.answer = 'Waiting for you to stop typing...'
                this.getAnswer()
            }
        },
        methods: {
            // `_.debounce` 是一個通過 Lodash 限制操作頻率的函數。
            // 在這個例子中,我們希望限制訪問 yesno.wtf/api 的頻率
            // AJAX 請求直到用戶輸入完畢纔會發出。想要了解更多關於
            // `_.debounce` 函數 (及其近親 `_.throttle`) 的知識,
            // 請參考:https://lodash.com/docs#debounce
            getAnswer: _.debounce(
                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
                        })
                },
                // 這是我們爲判定用戶停止輸入等待的毫秒數
                500
            )
        }
    })
</script>

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章