vue3.0 watch监听器使用方法

2021-01-21  本文已影响0人  累累的

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]
})
上一篇 下一篇

猜你喜欢

热点阅读