vue 計算屬性computed與methods

我們可以將同一函數定義爲一個方法而不是一個計算屬性。兩種方式的最終結果確實是完全相同的。然而,不同的是計算屬性是基於它們的響應式依賴進行緩存的。只在相關響應式依賴發生改變時它們纔會重新求值。

 <div id="nav">
        <h1>{{msg}}</h1>
        <p class="test1">{{mTime()}}</p>
        <p class="test2-1">{{mTime()}}</p>
        <p class="test2-2">{{mTime()}}</p>
        <p class="test2-3">{{mTime()}}</p>
        <p class="test3-1">{{timeNow}}</p>
        <p class="test3-2">{{timeNow}}</p>
        <p @click="getCLick">點擊我</p>
    </div>
var nav = new Vue({
      el:'#nav',
      data:{
        msg:'我是測試數據。。。'
      },
      computed: {
        timeNow(){
            console.log('%ctime。。。', 'color: green;')
            return this.msg+'computed'
        }
      },
      methods:{
        mTime(){
            console.log('%ctime。。。', 'color: red;')
            return this.msg+'methods'
        },
        getCLick(){
            this.msg='我變了'
            console.log('觸發點擊')
        }
      },
    });

 如圖,methods會執行四次,而計算屬性只執行一次。當點擊改變msg的值時,同樣的結果,methods執行四次,計算屬性執行一次。

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