vue3.0 watch监听器使用方法

watch监听器使用方法

  1. watch监听器可以监听一个getter函数
    • 这个getter要返回一个响应式对象
    • 当该对象更新后,会执行对应的回调函
import { reactive, watch } from 'vue'
const state = reactive({ count: 0 })
watch(() => state.count, (newValue, oldValue) => {
    // 因为watch被观察的对象只能是getter/effect函数、ref、热active对象或者这些类型是数组
    // 所以需要将state.count变成getter函数
})

2.watch可以监听响应式对象

import { ref, watch } from 'vue' 
const count = ref(0) 
watch(count, (newValue, oldValue) => {
})

3.watch可以监听多个响应式对线,任何一个响应式对象更新,就会执行回调函数

import { ref, watch } from 'vue' 
const count = ref(0) 
const count2 = ref(1) 
watch([count, count2], ([newCount, newCount2], [oldCount, oldCount2]) => { 
})
//还有第二种写法
watch([count, count2], (newValue, oldVlaue) => {
    console.log(newValue)//[newCount, newCount2]
    console.log(oldValue)//[oldCount, oldCount2]
})
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容