Vue 3 中 watch 监听的应用技巧

144 阅读2分钟

在 Vue 3 中,watch 的使用方式与 Vue 2 有所不同,主要是因为 Vue 3 引入了 Composition API,使得状态管理和副作用处理更加灵活和模块化。下面列出了一些 Vue 3 中 watch 监听的应用技巧:

1、监听单一的响应式引用(Ref) 当你有一个 ref 并且想在其值发生变化时执行某些操作,你可以直接使用 watch 函数来监听这个 ref。

   import { ref, watch } from 'vue'

   const count = ref(0)

   watch(count, (newValue, oldValue) => {
     console.log(`Count changed from ${oldValue} to ${newValue}`)
   })

2、监听多个响应式引用 如果你想同时监听多个 ref,可以使用一个箭头函数返回一个对象,其中的键对应 ref 名称,值为 ref 本身。

   const count = ref(0)
   const name = ref('John')

   watch([count, name], ([newCount, newName], [oldCount, oldName]) => {
     console.log(`Count changed from ${oldCount} to ${newCount}`)
     console.log(`Name changed from ${oldName} to ${newName}`)
   }, { deep: true })

3、监听响应式对象(Reactive) 对于整个响应式对象,你可以直接传入该对象并设置 deep 选项为 true。

   import { reactive, watch } from 'vue'

   const state = reactive({ count: 0 })

   watch(state, (newState, oldState) => {
     console.log('State changed')
   }, { deep: true })

4、监听对象的特定属性 如果你只想监听对象中的特定属性,可以使用箭头函数返回一个对象,其中的键是你要监听的属性名。

   const state = reactive({ count: 0, name: 'John' })

   watch(() => ({ count: state.count }), (newVal, oldVal) => {
     console.log(`Count changed from ${oldVal.count} to ${newVal.count}`)
   })

5、使用 watchEffect watchEffect 是 Vue 3 新增的一个功能,它会自动追踪依赖并在依赖更新时运行副作用。它非常适合用于那些不需要显式传入被观察的引用或对象的场景。

   const count = ref(0)

   watchEffect(() => {
     console.log(`Count is now ${count.value}`)
   })

6、立即执行监听 通过设置 immediate 选项为 true,可以在组件挂载后立即执行监听器一次。

   watch(count, (newValue, oldValue) => {
     console.log(`Count changed from ${oldValue} to ${newValue}`)
   }, { immediate: true })

7、清理副作用 watch 函数返回一个函数,这个函数可以用来取消监听。这在组件销毁或者不再需要监听时很有用。

   let stop

   setup() {
     stop = watch(count, (newValue, oldValue) => {
       // ...
     })

     onUnmounted(stop)
   }

这些技巧可以帮助你在 Vue 3 中更有效地使用 watch 功能来响应状态变化。