Vue Composition API - 无法向对象添加 属性

Vue Composition API - Can't add a property to an object

我正在使用 Vue 的组合 API。当我编写一些将 属性 添加到 ref 对象的代码时,模板渲染器似乎没有检测到更改。这是我的代码:

<template>
  <div id="app">
    <button @click="updateObj">Click</button>
    <div v-if="obj[1]">{{ obj[1] }}</div>
  </div>
</template>

<script>
import { defineComponent, ref } from "@vue/composition-api";

export default defineComponent({
  name: "App",
  setup() {
    const obj = ref({});

    const updateObj = () => {
      obj.value[1] = "hello";
      console.log(obj.value);
    };

    return {
      obj,
      updateObj,
    };
  },
});
</script>

单击按钮调用 updateObj,然后将 obj 上的 属性“1”设置为“hello”。如果设置了 obj[1],您应该会在浏览器中看到“hello”,但什么也没有显示。 Here's a codepen to the demo.

我已经使用 Composition API 几个月了,感觉我已经掌握了它的窍门,但我不知道这里发生了什么。我也试过 reactive 而不是 ref 但还是不行。

当你使用原始值时,你应该使用 ref,如果你想使用一个对象,你必须使用 reactive,在 the official docs 他们说:

If using ref, we are largely translating style (1) to a more verbose equivalent using refs (in order to make the primitive values reactive).

  • Using reactive is nearly identical to style (2). We only need to create the object with reactive and that's it.
  • Using reactive is nearly identical to style (2). We only need to create the object with reactive and that's it.

...
Use ref and reactive just like how you'd declare primitive type variables and object variables in normal JavaScript. It is recommended to use a type system with IDE support when using this style.

要使其具有反应性,请将对象直接分配给 ref 的值:

 obj.value = { 1: "hello" };

LIVE DEMO

我在这里添加我的答案,所以当我在六个月后再次 google 时,我会找到它。

如果您在 Vue 2 中使用组合 api,则需要使用 set 将新的跟踪 属性 添加到对象。

来自https://github.com/vuejs/composition-api

⚠️ set and del workaround for adding and deleting reactive properties ⚠️ Warning: set and del do NOT exist in Vue 3. We provide them as a workaround here, due to the limitation of Vue 2.x reactivity system.

In Vue 2, you will need to call set to track new keys on an object(similar to Vue.set but for reactive objects created by the Composition API). In Vue 3, you can just assign them like normal objects.

Similarly, in Vue 2 you will need to call del to ensure a key deletion triggers view updates in reactive objects (similar to Vue.delete but for reactive objects created by the Composition API). In Vue 3 you can just delete them by calling delete foo.bar.

<template>
  <div id="app">
    <button @click="updateObj">Click</button>
    <div v-if="obj[1]">{{ obj[1] }}</div>
  </div>
</template>

<script>
import { defineComponent, ref, set } from "@vue/composition-api";

export default defineComponent({
  name: "App",
  setup() {
    const obj = ref({});

    const updateObj = () => {
      set(obj.value, 1, "hello");
      console.log(obj.value);
    };

    return {
      obj,
      updateObj,
    };
  },
});
</script>

LIVE DEMO