关于Vue中用watch监视不同类型的响应式变量

<<<使用ref绑定的变量>>>

1.数值类型变量

const num = ref(1)
//方法一
watch(num, (newValue, oldValue) => {
  console.log(newValue, oldValue) // 数值
})
//方法二
watch(() => num.value, (newVal, oldVal) => {
  // 也能正常工作,但不如方式一简洁
  console.log('数值变化:', oldVal, '->', newVal)
})

2.引用类型变量

2.1.整体监视

const state = ref({ count: 0 });
//方法一
watch(state, (newVal, oldVal) => {
  console.log('state changed:', newVal, oldVal);
}, { deep: true });
//方法二
watch(() => state.value, (newVal, oldVal) => {
  console.log('state.value changed:', newVal, oldVal);
}, { deep: true });

2.2.只监视其中的特定属性

const state = ref({ count: 0 });
watch(() => state.value.count, (newVal, oldVal) => {
  console.log('count changed:', newVal, oldVal);
});

<<<使用reactive绑定的引用类型变量>>>

const state = reactive({ count: 0 })
watch(() => state.count, (newVal) => {
  console.log('state.count:', newVal)  // 需要 getter 函数
})

// 如果直接 watch state,需要 deep: true
watch(state, (newVal) => {
  console.log('整个 state 变化')
}, { deep: true })

<<<补充:对于store中的状态和computed变量的监视>>>

1.store中的状态

const store = useStore()
watch(() => store.someState, callback)  // 需要 getter

2.computed变量

const double = computed(() => count.value * 2)
watch(double, callback)  // 可以直接传递 computed
posted @ 2025-12-12 12:43  wenerda  阅读(0)  评论(0)    收藏  举报