Vue3 watch 偵聽 props 的變化


watch 有兩種寫法

// 偵聽一個 getter
const state = reactive({ count: 0 })
watch(
  () => state.count,
  (count, prevCount) => {
    /* ... */
  }
)

// 直接偵聽一個 ref
const count = ref(0)
watch(count, (count, prevCount) => {
  /* ... */
})

如果我們想偵聽 props 上的屬性變化,需要采用第一種寫法

// 假設 props 上有個 name 屬性
// 下面的寫法會生效
watch(
  () => props.name,
  (count, prevCount) => {
    /* ... */
  }
)

// 下面的寫法不會被觸發
watch(props.name, (count, prevCount) => {
  /* ... */
})


免責聲明!

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



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