Vue使用组合API更新数组状态

时间:2020-09-24 05:51:15

标签: typescript vue.js vue-composition-api

我正在尝试使用vue 3中的组合api和以下文件创建某种状态:

// useNotifications.ts
const state = reactive<Array<Notification>>([]);

export function useNotifications() {
  return {
    state,
    add: (notification: Notification) => {
      state.push(notification);
    },
  };
}

此通知状态从以下内容读取并以html格式呈现:

// TheNotifications.vue
setup() {
    const notifications = useNotifications();

    let first = notifications.state[0];

    return {
      first,
    };
  },

通知会在某种形式的提交事件中添加,例如:

// SomeForm.vue
notifications.add({ type: "success", text: "Food added" });

但是,TheNotifications在推送​​时从未看到更改。我尝试了一些不同的方法,例如使用toRef,但没有成功。我是这个合成api的新手,我想知道我缺少什么。

1 个答案:

答案 0 :(得分:1)

reactive不适用于数组。似乎是对api的限制。您可以阅读类似的讨论here

使用ref代替reactive,它应该可以正常工作。我已经建立了一些这样的应用程序,可以确认它是否正常运行。 因此写:const state = ref<Array<Notification>>([]);,您将使其正常运行。根据经验,在对象之外的任何地方都使用ref,那是您要使用reactive的时候。比这要复杂得多,但是如果您像这样使用它们,它将始终有效。