考虑以下说明性示例:
const useFeatureX = () => {
return Vue.reactive({
x1: 2,
x2: 3
});
};
const useFeatureY = () => {
return Vue.reactive({
y1: 1,
y2: 2
});
};
const App = {
setup() {
return { ...useFeatureX(), ...useFeatureY() };
}
};
Vue.createApp(App).mount("#root");
input {
max-width: 50px;
}
<script src="https://unpkg.com/vue@next"></script>
<div id="root">
x1 + x2: <input type="number" v-model="x1"/> + <input type="number" v-model="x2"/> = {{ +x1 + +x2 }} <br/>
y1 + y2: <input type="number" v-model="y1"/> + <input type="number" v-model="y2"/> = {{ +y1 + +y2 }}
</div>
如您所见,在运行代码段时,将
useFeatureX()
和useFeatureY()
中的两个对象合并为一个{ ...useFeatureX(), ...useFeatureY() }
后,该应用程序不再跟踪更新。如何在不失去 react 性的情况下合并两个 react 性对象?
最佳答案
Object destructuring breaks reactivity。
相反,您可以使用
toRefs
至
“将 react 性对象转换为简单对象,在该对象中每个属性
生成的对象是指向相应属性的ref
原始对象”。
const useFeatureX = () => {
return Vue.reactive({
x1: 2,
x2: 3
});
};
const useFeatureY = () => {
return Vue.reactive({
y1: 1,
y2: 2
});
};
const App = {
setup() {
return { ...Vue.toRefs(useFeatureX()), ...Vue.toRefs(useFeatureY()) };
}
};
Vue.createApp(App).mount("#root");
input {
max-width: 50px;
}
<script src="https://unpkg.com/vue@next"></script>
<div id="root">
x1 + x2: <input type="number" v-model="x1"/> + <input type="number" v-model="x2"/> = {{ +x1 + +x2 }} <br/>
y1 + y2: <input type="number" v-model="y1"/> + <input type="number" v-model="y2"/> = {{ +y1 + +y2 }}
</div>