Vue3 TS 响应式问题:toRefs 函数导致非响应式数据
在 Vue3 TS 中,使用 toRefs 函数将 reactive 对象转换为 ref 对象,可能会导致数据非响应式。这是因为 ref 对象的 value 属性才是响应式的,而不是 ref 对象本身。
问题代码示例:
export interface GlobalConfigure {
SetTop: boolean; // 设置置顶
RemoveSource: boolean; // 移除源件
RemoveRestore: boolean; // 移除还原
AutomaticStartUp: boolean; // 开机自启动
[key: string]: boolean; // 接受任何字符串密钥的索引签名
}
const globalConfigure: GlobalConfigure = reactive({
SetTop: false, // 设置置顶
AutomaticStartUp: false, // 开机自启动
RemoveSource: false, // 移除源件
RemoveRestore: true, // 移除还原
});
Object.keys(toRefs(globalConfigure)).forEach((key) => {
// 匹配是否为需要更新key
if (changeAttribute === key) {
// 重置更新值
globalConfigure[key] = change;
}
});
解决方法:
将 globalConfigure 声明为 ref 对象,并在访问和修改属性时加上 value。
const globalConfigure = reactive<GlobalConfigure>({ // 修改为 ref 对象
SetTop: false,
AutomaticStartUp: false,
RemoveSource: false,
RemoveRestore: true,
});
Object.keys(globalConfigure).forEach((key) => {
if (changeAttribute === key) {
globalConfigure[key as keyof GlobalConfigure].value = change; // 添加 .value
}
});
注意:
-
在修改属性值时,需要使用
globalConfigure[key as keyof GlobalConfigure].value = change,将key强制转换成keyof GlobalConfigure类型,以避免类型错误。 -
如果想要在模板中直接使用
globalConfigure的属性,可以使用toRefs函数将其转换成ref对象并解构出来:
const { SetTop, AutomaticStartUp, RemoveSource, RemoveRestore } = toRefs(globalConfigure);
然后就可以直接在模板中使用这些属性了。
原文地址: https://www.cveoy.top/t/topic/nQio 著作权归作者所有。请勿转载和采集!