简体   繁体   English

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

[英]Vue update array state using the composition api

I'm trying to create some kind of state using the composition api in vue 3 with the following file:我正在尝试使用具有以下文件的 vue 3 中的组合 api 创建某种状态:

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

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

This notification state is read and rendered in html from this the below:这个通知状态从下面的 html 中读取和呈现:

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

    let first = notifications.state[0];

    return {
      first,
    };
  },

And notifications are added at some form submit event like so:并在某些表单提交事件中添加通知,如下所示:

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

However, TheNotifications never sees the changes when pushing.但是, TheNotifications在推送时永远不会看到更改。 I tried some different methods, for example with toRef , but I had no success.我尝试了一些不同的方法,例如使用toRef ,但没有成功。 I'm new to this composition api thing and I was wondering what I'm missing.我是这个组合 api 的新手,我想知道我错过了什么。

reactive doesn't work with Arrays. reactive不适用于数组。 Seems to be a limitation of the composition api.似乎是组合 api 的限制。 You can read a similar discussion here .您可以在此处阅读类似的讨论。

Use ref instead of reactive , it should work fine.使用ref而不是reactive ,它应该可以正常工作。 I have built a few apps like this and can confirm it working.我已经构建了一些这样的应用程序,并且可以确认它工作正常。 So write: const state = ref<Array<Notification>>([]);所以写: const state = ref<Array<Notification>>([]); , you will have it working. ,您将可以使用它。 And as a rule of thumb, use ref for anything but objects, that's when you want to use reactive .根据经验,除了对象之外的任何东西都使用ref ,那就是你想要使用reactive It's more complex than that but if you use them like this, it will always work.它比这更复杂,但如果您像这样使用它们,它将始终有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM