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);
})
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值