A watch source can only be a getter/efefct function, a ref, a reactive object, or an array of these

A watch source can only be a getter/efefct function, a ref, a reactive object, or an array of these types.
原因

Vue3 Watch 的source 接受的参数不符合要求,只能接受一个getter, efefct, ref,reactive或者元素是这几个类型的数组。

<script setup>
    import { computed, effect, reactive, ref, toRefs, watch, watchEffect } from "vue";
	// 定义Ref数据
	const count = ref(10);
    const doubleCount = ref(20);
	// 定义一个常量
	const Pi = 3.14
    // 定义一个reactive 对象
    const toRefsData = reactive({
      name: "阿木",
      hobiy: "drink",
    })
</script>
watch 监听常量
// [Vue warn]: Invalid watch source:  3.14 A watch source can only be a getter/effect function, a ref, a reactive object, or an array of these types. 
watch(Pi,(newValue,oldValue)=>{
  console.log("watch-Pi:",newValue,oldValue);
})

// 如果用一个函数返回那么就可以消除警告,但是没有意思,因为PI不是响应式
watch(()=>Pi,(newValue,oldValue)=>{
  console.log("watch-Pi:",newValue,oldValue);
})
watch 监听 ref
const ChangeCount = (name)=>{
    count.value = count.value + 1;
}
// 可以监听
watch(count,(newValue,oldValue)=>{
  console.log("watch-count:",newValue,oldValue);
})
// 没有警告,但是监听不到
watch(()=>count,(newValue,oldValue)=>{
  console.log("watch-count:",newValue,oldValue);
})
watch 监听 reactive
// 直接解构,name 将会失去响应式
const { name } = toRefsData;.
// 使用 toRefs 解构之后,还是会有响应式
const { hobiy } = toRefs(toRefsData);

// 可以监听toRefsData
watch(toRefsData,(newValue,oldValue)=>{
  console.log("watch-toRefsData:",newValue,oldValue);
})

// hobiy通过toRefs解构,可以监听到
watch(hobiy,(newValue,oldValue)=>{
  console.log("watch-hobiy:",newValue,oldValue);
})
// 警告,因为name 已经失去了响应式	
watch(name,(newValue,oldValue)=>{
  console.log("watch-name:",newValue,oldValue);
})
watch 监听 effect
// count发生改变的时候,触发此effect
const effectDoubleCount = effect(()=>{
  console.log('通过effect改变doubleCount')
  doubleCount.value =  count.value * 2
})

// 监听不到,但是也不报错,为什么呢?我也不明白
watch(effectDoubleCount,(newValue,oldValue)=>{
  console.log("watch-count:",newValue,oldValue);
})
watch 监听 getter

通过找资料是 getter 应该指的是vuex的getter,这里就不实验了、

watch 监听 多个source
watch([count,hobiy,effectDoubleCount],(newValue,oldValue)=>{
  console.log("watch-hobiy:",newValue,oldValue);
})

你可能感兴趣的:(报错,javascript,vue.js,前端)