侦听器watch
一、 watch API 我们先看看 watch的使用例子,watch 有多种用法,可以接收多种类型参数: import { reactive, watch } from 'vue' // 1. 传入getter函数 const state = reactive({ count: 0 }) watch(() => state.count, (count, prevCount) => { // 当 state.count 更新,会触发此回调函数 }) // 2. 传入reactive对象 watch(state, (count, prevCount) => { // 当 state.count 更新,会触发此回调函数 }) // 3. 传入ref对象 const stateRef = ref(0) watch(stateRef, (count, prevCount) => { // 当 stateRef.value 更新,会触发此回调函数 }) // 4.监听多个数据源,回调函数接受两个数组,分别对应来源数组中的新值和旧值: watch([fooRef, barRef], ([foo, bar], [prevFoo, prevBar]) => { /* ... */ }) 从上面的例子可以看到,对于 watch,它能接收的第一个参数类型非常多。 你可以传入一个ref对象、一个响应式对象、一个 getter 函数、甚至是一个数组。 我们在上一篇中知道了computed对象其内部是借助了 effect函数 创建了一个 reactiveEffect函数,在访问computed对象的值时,执行其 runner函数 求值。 ...