【问题标题】:Vue update array state using the composition apiVue 使用组合 api 更新数组状态
【发布时间】:2021-01-10 09:09:14
【问题描述】:

我正在尝试使用 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 的新手,我想知道我错过了什么。

【问题讨论】:

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


    【解决方案1】:

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

    使用ref 而不是reactive,应该可以正常工作。我已经构建了一些这样的应用程序,并且可以确认它可以正常工作。 所以写:const state = ref&lt;Array&lt;Notification&gt;&gt;([]);,你会让它工作的。根据经验,ref 用于除对象之外的任何内容,这就是您想要使用reactive 的时候。它比这更复杂,但如果你像这样使用它们,它总是可以工作的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-03
      • 2019-08-06
      • 2022-07-16
      • 1970-01-01
      • 2020-12-22
      • 1970-01-01
      相关资源
      最近更新 更多