gpt4 book ai didi

javascript - Vue : how to merge two reactive objects without loosing reactivity

转载 作者:行者123 更新时间:2023-12-03 06:39:20 26 4
gpt4 key购买 nike

考虑这个说明性示例:

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 .

When we want to use a few properties of the large reactive object, it could be tempting to use ES6 destructuringto get properties we want:

[...]

Unfortunately, with such a destructuring the reactivity for bothproperties would be lost. For such a case, we need to convert ourreactive object to a set of refs. These refs will retain the reactiveconnection to the source object:


相反,您可以使用
toRefs
"[convert] 一个 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>

关于javascript - Vue : how to merge two reactive objects without loosing reactivity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64099203/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com