:::

2-4 watch 及 watchEffect 監聽

  1. watch用來監聽某個值
    watch(被監聽變數, (新值, 舊值) => {
      要做的事...
    });

     

    1. 若是監聽 ref 的值,那就直接監聽該值即可
    2. 若是監聽 ref 物件的值,那要針對其中的資料,並將之改成 getter 可讀取的值,也就是 () => refObj.value.idx 這種方式
    3. 若是監聽 ref 整個物件,那要加入第三個參數來做深層監控,也就是 {deep: true} 才行,無法取得舊值
    4. 若是監聽 reactive 物件的值,那要針對其中的資料,並將之改成 getter 可讀取的值,也就是 () => reactiveObj.idx 這種方式
    5. 若是監聽 reactive 整個物件,無法取得舊值
  2. watchEffect(()=>{})用來監聽,且不須傳入欲監聽參數,只要在{}中直接使用參數值,就會自動監聽
    watchEffect(() => {
      console.log(num.value);
    });

     

  3. 例如:
    <script>
    const { ref, reactive, watch, watchEffect } = Vue;
    const App = {
      setup() {
        const num = ref(0);
        const refObj = ref({ idx: 0 });
        const reactiveObj = reactive({ idx: 0 });
        let timer = null;
    
        watch(num, (newNum, oldNum) => {
          console.log(
            "ref 資料" + num.value + " 的監控",
            "新:" + newNum + ",舊:" + oldNum
          );
        });
    
        watch(
          () => refObj.value.idx,
          (newNum, oldNum) => {
            console.log(
              "ref 單一物件 getter=" + refObj.value.idx + " 的監控",
              "新:" + newNum + ",舊:" + oldNum
            );
          }
        );
    
        watch(
          refObj,
          (newNum, oldNum) => {
            console.log(
              "ref 整個物件=" + refObj.value.idx + " 的深層監控",
              "新:" + newNum.idx + ",舊:" + oldNum.idx
            );
          },
          {
            deep: true,
          }
        );
    
        watch(
          () => reactiveObj.idx,
          (newIdx, oldIdx) => {
            console.log(
              "reactive 單一物件 getter=" + reactiveObj.idx + " 的監控",
              "新:" + newIdx + ",舊:" + oldIdx
            );
          }
        );
    
        watch(reactiveObj, (newObj, oldObj) => {
          console.log(
            "reactive 整個物件=" + reactiveObj.idx + " 的監控",
            "新:" + newObj.idx + ",舊:" + oldObj.idx
          );
        });
    
        watchEffect(() => {
          console.log("watchEffect 監控 ref 資料 = " + num.value);
          console.log("watchEffect 監控 ref 物件 = " + refObj.value.idx);
          console.log("watchEffect 監控 reactive 物件 = " + reactiveObj.idx);
        });
    
        timer = setInterval(() => {
          console.log("-------");
          num.value++;
          refObj.value.idx++;
          reactiveObj.idx++;
          if (num.value > 4) {
            clearInterval(timer);
          }
        }, 2000);
    
        return {};
      },
    };
    
    Vue.createApp(App).mount("#app");
    </script>
    

     

完整範例:


:::

書籍目錄

展開 | 闔起

快速登入


http%3A%2F%2Fcampus-xoops.tn.edu.tw%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbdsn%3D1729%26tbsn%3D33

計數器

今天: 1003100310031003
昨天: 3068306830683068
總計: 8077508807750880775088077508807750880775088077508