methods、computed與watch的不同


Posted by hoyi-23 on 2021-08-06

methods

把畫面與資料綁在一起,需要有事件觸發(例如: click、keyup等等),觸發後會影響畫面與資料。

computed

computed是一個計算屬性,只有在相關依賴發生改變時才會重新求值。
針對輸出到畫面的內容做處理,常用在(過濾)。

  • 會影響畫面
  • 不會影響資料
  • 可以省略觸發!!!
  • 要使用return把資料回傳

觸發的意思就是,幫我們要搜尋並過濾東西,需要在填好 輸入框 後,按下觸發按鈕,才會進行過濾與畫面渲染。
而 Computed 可以減少掉 觸發按鈕 這件事! 它只要發現 輸入框 的內容資料改變,就可以直接進行過濾與畫面渲染。

<input type="text" v-model="filterText">
<ul>
    <li v-for="item in filterArray" :key="item.id">
    {{item}}
    </li>
</ul>

computed:{
    filterArray: function(){
        var vm = this; //當我們在內部進行filter時,this指向會跑調
        return vm.arrayData.filter(function(item){
            return item.name.match(vm.filterText)
            //只要filterText 的 輸入欄 值 改變 就會直接觸發
        })
    }
}

若是遇到資料量很大時,computed的效能就會受到影響。

使用 computed 將timestampe 轉為時間格式

有時候後端會用穿入 timestampe 的方式傳入時間,我們就可以運用computed將時間數字串轉為時間格式。
範例: 當執行結束就會跑一次timestampe

CodePen 實例

{{newDate}}

<script>
computed:{
    formatTime(){
    console.log(this.newDate);
    //因為 timestamp 取得的是秒數,但在 JavaScript 中要帶入的是毫秒,所以要 new Date(timestamp * 1000)
    var dates = new Date(this.newDate * 1000);
    var year = dates.getFullYear();
    var month = dates.getMonth() + 1;
    var date = dates.getDate() + 1;
    var hours = dates.getHours();
    var minutes = dates.getMinutes();
    var seconds = dates.getSeconds();
    return `${year}/${month}/${date}/${hours}/${minutes}/${seconds}`
    }
},
mounted(){
    //這邊要取得的是 timestamp
    // (Date.now()取得的是毫秒數,如果要讓阿變成 timestamp 要除1000,因為TimeStamp 是以秒數呈現)
this.newDate = Math.floor(Date.now()/1000);
}
</script>

Date() 參考筆記

watch

當特定變數產生變化時,會執行的function
Watch 真的覺得和 Computed 很難區分,其中不同的點:

watch 較適合做非同步的操做, computed 無法這樣操作。
( 非同步: watch 可以在監聽到特定變數改變時,在一段時間後執行setTimeout() )


方法 比較
methods 必須要有一定的觸發條件才能執行
如點擊事件
computed HTML DOM加載後馬上執行的
等到依賴資料改變時才會再次求值
watch 適合做非同步的操做

#methods #Computed #watch







Related Posts

資訊安全概念

資訊安全概念

interface & 與type的比較

interface & 與type的比較

Day 9 - Dictionary

Day 9 - Dictionary


Comments