如果我观看解构的道具,Vue 3 手表将无法工作 [英] Vue 3 watch doesn’t work if I watch a destructured prop
问题描述
我正在尝试在 Vue 3 中观看道具,但奇怪的是,当我解构它时,观察者不起作用.但没有解构它按预期工作.我在这里错过了什么?
I am trying to watch a prop in Vue 3 but it is strange that when I destructure it then the watcher doesn't work. But without destructuring it works as expected. What am I missing here?
P.S.我正在使用 Vue 3 + Vite
这不起作用
export default {
props: {
modelValue: {
type: Boolean,
default: false,
},
},
setup({ modelValue }, context)
{
watch(() => modelValue, (newValue, oldValue) => {
console.log(newValue)
})
},
}
但是如果我不对其进行解构,那么它会起作用
But if I don’t destructure it then it works
setup(props, context) {
watch(() => props.modelValue, (newValue, oldValue) => {
console.log(newValue)
})
}
推荐答案
props
传入 setup
是 reactive 对象,并且所有反应性都与围绕对象本身的代理紧密相关.
props
passed into setup
is reactive object and all reactivity is tight to the proxy around the object itself.
如果您取此类对象的属性值,您将得到:
If you take a value of the property of such object, you get either:
- 对象(如果值是对象),也是反应式的
- 自身不能响应的值(例如整数)
解构就是赋值:
const { modelValue } = props
...等同于:
const modelValue = props.modelValue
您可以按照 中所述使用 toRefs
文档
You can use toRefs
as described in docs
export default {
props: {
modelValue: {
type: Boolean,
default: false,
},
},
setup(props, context)
{
let { modelValue } = toRefs(props)
watch(modelValue, (newValue, oldValue) => {
console.log(newValue)
})
},
}
现在 modelValue
是 ref 所以它可以作为 watch
的第一个参数传递(不需要函数)并且在大多数地方你必须使用 modelValue.Value
来获取它的值
Now modelValue
is ref so it can be passed as first argument of watch
(no need to for a function) and in most places you must use modelValue.Value
to get it's value
这篇关于如果我观看解构的道具,Vue 3 手表将无法工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!