LESSON-20 · TOPIC 03

computed 與 method

能用 computed 表示可快取的衍生值,用一般函式表達每次呼叫的動作,並比較執行次數。

code-editVue 反應式資料與清單渲染|computed 與 method本頁只練一個責任

本頁只練什麼

能用 computed 表示可快取的衍生值,用一般函式表達每次呼叫的動作,並比較執行次數。

把衍生資料複製成第二份狀態容易不同步;把有副作用的動作藏進 computed 又會破壞可預測性。

要修改的檔案:files/starter/main.js

定位:把 counter 寫在 getter 與 method 內,不要只數讀取端。|依 starter-3 定位,只修改「computed 與 method」的責任。

任務情境

先結果,再原理;完成後要能說出自己看見的證據。

現在的問題

服務清單每次畫面更新都重跑昂貴篩選,即使搜尋條件沒變。

起始狀態:count=2,兩種執行計數為0。

完成後要看到

computedRuns=1、methodRuns=2、computedValue=4、methodValue=4。

驗收證據:computedRuns=1、methodRuns=2、兩者值皆4

何時會用到

篩選、總價、顯示文字用 computed;送出、切換或每次都要執行的程序用 method。

常見混淆:computed 不是永遠只算一次;依賴變更後下一次讀取會重新計算。

觀念與最小範例

這段程式是理解起點,不是要你直接跳過 Starter。

computed 與 method Computed cached derivation and method execution

computed 像有記憶的計算結果;method 每叫一次就重新做一次。

正式說法:computed ref 依 reactive dependencies cache getter result;method/function 在每次 invocation 執行 body。

const doubled=computed(()=>{runs++;return count.value*2}); const calculate=()=>{calls++;return count.value*2}。

三步完成本主題

每一步都留下可觀察結果;如果沒看到,先看「卡住先查」。

  1. Step 1|先看見目前缺口,不急著貼答案。

    檔案:files/starter/main.js 定位:把 counter 寫在 getter 與 method 內,不要只數讀取端。

    要做:先重新載入 Starter,記錄目前畫面、DOM、Computed、Console 或文件內容。

    預期:能指出「把 counter 寫在 getter 與 method 內,不要只數讀取端。」目前的缺口。

    證據:保存 files/starter/main.js 的目前狀態,並指出下一步只會修改哪個檔案責任。

    卡住先查:確認開啟的是 files/starter/main.js,且定位到 把 counter 寫在 getter 與 method 內,不要只數讀取端。。

  2. Step 2|只修改本主題的一個責任。

    檔案:files/starter/main.js 定位:把 counter 寫在 getter 與 method 內,不要只數讀取端。

    要做:在依賴不變時各讀/呼叫兩次,輸出結果與執行次數。

    預期:computedRuns=1、methodRuns=2、computedValue=4、methodValue=4。

    證據:computedRuns=1、methodRuns=2、兩者值皆4

    卡住先查:把 counter 寫在 getter 與 method 內,不要只數讀取端。

  3. Step 3|重新載入並以證據驗收,不以『看起來差不多』判定完成。

    檔案:files/starter/main.js 定位:把 counter 寫在 getter 與 method 內,不要只數讀取端。

    要做:重新整理頁面,再逐項比對預期結果與 evidence。

    預期:computedRuns=1、methodRuns=2、computedValue=4、methodValue=4。

    證據:computedRuns=1、methodRuns=2、兩者值皆4

    卡住先查:把 counter 寫在 getter 與 method 內,不要只數讀取端。

觀察示範

這個示範只讓你看懂概念,不會替你修改 Starter,也不會自動宣告完成。

computed 與 methodruntime fixture · read-only demo
本主題示範畫面:

驗收證據

勾選只是學習紀錄;真正完成仍要回到 Starter 的實際結果。

提示 1|方向

依賴不要變,只比較連續兩次讀取。

提示 2|關鍵片段

讀 doubled.value 兩次;呼叫 calculate() 兩次。

提示 3|完整解答與原因

完整解答與原因:count 不變時 computed getter 第一次計算後快取,因此 runs=1;method 每次呼叫都執行,calls=2,兩者結果同為4。

完成後進入下一階段,或回到入口選下一個 topic。

開始 Starter →回到主題清單