我有这个 .ts 文件:
import { reactive, toRefs } from 'vue'
export const TitleComponent = () => {
const obj = reactive({
title: "This should be reactive"
})
const updateObj = () => {
obj.title = 'This is now different'
}
return {...toRefs(obj), updateObj }
}
然后我将其导入到显示它的 vue 组件中
<template>
<h1>{{ title }}</h1>
</template>
import { defineComponent } from 'vue'
import { TitleComponent } from 'some/place'
export default defineComponent({
const { title } = TitleComponent()
return { title }
})
然后,我在运行该方法的另一个组件中使用函数 updateObj
。但它不会更新标题值。给出了什么?
<template>
<button @click="updateObj">Click Me</button>
</template>
import { defineComponent } from 'vue'
import { TitleComponent } from 'some/place'
export default defineComponent({
const { updateObj } = TitleComponent()
return { updateObj}
})
最佳答案
将 obj
移至 export const TitleComponent = () => {}
之外。
import { reactive, toRefs } from 'vue';
const obj = reactive({
title: 'This should be reactive'
});
export const TitleComponent = () => {
const updateObj = () => {
obj.title = 'This is now different'
};
return { ...toRefs(obj), updateObj };
}
当您在其中导入/调用 TitleComponent()
时,它每次都会创建一个 obj
的新实例。
关于javascript - Vue3 Reactive 值未按预期更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66996958/