vue3 watch 監聽數組 對象


解決方法(數組觸發兩次)

const numbers = reactive([1, 2, 3, 4])

watch(
  () => [...numbers],
  (numbers, prevNumbers) => {
    console.log(numbers, prevNumbers);
  })

numbers.push(5) // logs: [1,2,3,4,5] [1,2,3,4]

解決的問題

1、數組deep監聽觸發兩次
2、新舊值一致

對象

嘗試檢查深度嵌套對象或數組中的屬性更改仍然需要deep選項為true
Attempting to check for changes of properties in a deeply nested object or array will still require the deep option to be true

const state = reactive({ 
  id: 1, 
  attributes: { 
    name: "",
  },
});

watch(
  () => state,
  (state, prevState) => {
    console.log(
      "deep ",
      state.attributes.name,
      prevState.attributes.name
    );
  },
  { deep: true }
);

state.attributes.name = "Alex"; // Logs: "deep " "Alex" "Alex"

引用

vue3官方文檔


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM