Vue:如何在不失去反应性的情况下合并两个反应性对象

Vue: how to merge two reactive objects without loosing reactivity

考虑这个说明性的例子:

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() } 之后,应用程序不会跟踪更新没有了。

如何在不失去反应性的情况下合并两个反应性对象?

Object destructuring breaks reactivity.

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

[...]

Unfortunately, with such a destructuring the reactivity for both properties would be lost. For such a case, we need to convert our reactive object to a set of refs. These refs will retain the reactive connection to the source object:

相反,您可以使用 toRefs 至 “[将] 反应对象转换为普通对象,其中每个 属性 结果对象是指向相应 属性 的 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>