在玩Vue 3 Reactive时,我出现了一种我无法解释的行为.
我创造了一个原始人的ref
.在上面判断isRef
,显然返回true
.但是当作为prop
、isRef()
和isReactive()
传递给子组件时,返回false
.为什么?
此外,即使它们都返回false
,如果值发生更改,我在子组件中添加的这个props 的观察器也会被触发.如果观察值既不是ref
也不是reactive
,它怎么会触发呢?
下面是父进程和子进程的代码片段:
父级.查看
let foo = ref(0);
function changeFoo() {
foo.value++;
}
console.log("parent check is reactive?", isReactive(foo)); // retruns false
console.log("parent check is ref?", isRef(foo)); // retruns true
watch(foo, (value, oldValue) => {
console.log("foo changing from", oldValue, "to ", value);
});
Child.vue
const props = defineProps<{
foo: number;
}>();
console.log("child check is reactive?",isReactive(props), isReactive(props.foo)); // returns true false
console.log("child check is ref ?",isRef(props), isRef(props.foo)); // returns false false // Question 1: Why props.foo is not a Ref ?
watch(props, (value, oldValue) => {
console.log("props changing from", oldValue, " to ", value);
});
watch(()=>props.foo, (value, oldValue) => {
// Question 2: Why this Watcher detects changes of "foo" without it being a ref nor reactive ?
console.log("props.foo changing from ", oldValue, " to ", value);
});
和Vue SFCplayground here的链接
prize 问题:
当foo
被传递给子组件中使用的Composable时,除非我们通过toRef传递foo
,否则Composable内的观察器不会被触发,但如果foo
是一个ref/active对象,则不需要这个额外的步骤.为什么原语需要这个加法步骤?