溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

VUE3中watch監(jiān)聽使用的方法有哪些

發(fā)布時間:2022-06-07 13:39:00 來源:億速云 閱讀:1087 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“VUE3中watch監(jiān)聽使用的方法有哪些”,在日常操作中,相信很多人在VUE3中watch監(jiān)聽使用的方法有哪些問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”VUE3中watch監(jiān)聽使用的方法有哪些”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

    watch介紹

    vue中watch用來監(jiān)聽數(shù)據(jù)的響應(yīng)式變化.獲取數(shù)據(jù)變化前后的值

    watch的完整入?yún)?/p>

    watch(監(jiān)聽的數(shù)據(jù),副作用函數(shù),配置對象)
    watch(data, (newData, oldData) => {}, {immediate: true, deep: true})

    watch監(jiān)聽的不同情況

    創(chuàng)建響應(yīng)式數(shù)據(jù)

    import { ref, watch, reactive } from "vue";
    let name = ref("moxun");
    let age = ref(18);
    let person = reactive({
      Hobby: "photo",
      city: {
        jiangsu: {
          nanjing: "雨花臺",
        },
      },
    });

    1 監(jiān)聽單個refimpl數(shù)據(jù)

    watch(name, (newName, oldName) => {
      console.log("newName", newName);
    });

    2 監(jiān)聽多個refimpl數(shù)據(jù)

    方式一:vue3允許多個watch監(jiān)聽器存在

    watch(name, (newValue, oldValue) => {
      console.log("new", newValue, "old", oldValue);
    });
    watch(age, (newValue, oldValue) => {
      console.log("new", newValue, "old", oldValue);
    });

    方式二:將需要監(jiān)聽的數(shù)據(jù)添加到數(shù)組

    watch([name, age], (newValue, oldValue) => {
      // 返回的數(shù)據(jù)是數(shù)組
      console.log("new", newValue, "old", oldValue);
    });

    3 監(jiān)聽proxy數(shù)據(jù)

    注意

    1.此時vue3將強制開啟deep深度監(jiān)聽

    2.當監(jiān)聽值為proxy對象時,oldValue值將出現(xiàn)異常,此時與newValue相同

    // 監(jiān)聽proxy對象
    watch(person, (newValue, oldValue) => {
      console.log("newValue", newValue, "oldValue", oldValue);
    });

    4 監(jiān)聽proxy數(shù)據(jù)的某個屬性

    需要將監(jiān)聽值寫成函數(shù)返回形式,vue3無法直接監(jiān)聽對象的某個屬性變化

    watch(
      () => person.Hobby,
      (newValue, oldValue) => {
        console.log("newValue",newValue, "oldvalue", oldValue);
      }
    );

    注意

    當監(jiān)聽proxy對象的屬性為復(fù)雜數(shù)據(jù)類型時,需要開啟deep深度監(jiān)聽

    watch(
      () => person.city,
      (newvalue, oldvalue) => {
        console.log("person.city newvalue", newvalue, "oldvalue", oldvalue);
      },{
        deep: true
      }
    );

    5 監(jiān)聽proxy數(shù)據(jù)的某些屬性

    watch([() => person.age, () => person.name], (newValue, oldValue) => {
      // 此時newValue為數(shù)組
      console.log("person.age", newValue, oldValue);
    });

    到此,關(guān)于“VUE3中watch監(jiān)聽使用的方法有哪些”的學習就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

    向AI問一下細節(jié)

    免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI