【发布时间】:2021-05-09 19:07:38
【问题描述】:
我正在尝试(深入)观察 Vue 3 中反应性对象的任何变化:
import { reactive, watchEffect } from 'vue';
const settings = reactive({
panes: {
left: {
defaultAction: "openInOtherPane",
},
right: {
defaultAction: "openInThisPane",
},
},
showMenu: false,
isDrawerOpen: false,
});
watchEffect(() => {
console.log('The new settings are', settings);
});
// Try to change a setting (this does not trigger watchEffect)
settings.panes.left.defaultAction = "none";
这段代码有两个问题:
- 更改设置时不会触发 watchEffect
- console.log 以
Proxy { <target>: {…}, <handler>: {…} }的形式显示不可读的对象
我也试过watch:
watch(
() => settings,
settings => {
console.log('The new settings are', settings);
},
);
同样的问题。
当我只看对象上的一个属性时,它确实有效:
watchEffect(() => {
console.log('Is the menu shown:', settings.showMenu); // This works
});
通过解构,我可以看到更深层次的变化,但不能更深层次:
watchEffect(() => {
// This works one level deep
console.log('Settings are changed:', { ...settings });
});
可以使用 toRaw 记录设置,但不会触发 watchEffect:
import { toRaw, watchEffect } from 'vue';
watchEffect(() => {
// console.log shows the raw object, but watchEffect is not triggered
console.log('Settings are changed:', toRaw(settings) );
});
是否有一种优雅的方法可以观察反应对象中任何级别的属性变化?
【问题讨论】:
标签: javascript watch vuejs3 vue-composition-api vue-reactivity