Vue 使用组合 api 更新数组状态
Vue update array state using the 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,我想知道我错过了什么。
reactive
不适用于数组。似乎是构图的限制api。您可以阅读类似的讨论 here.
使用 ref
而不是 reactive
,它应该可以正常工作。我已经构建了一些这样的应用程序并且可以确认它可以正常工作。
所以写:const state = ref<Array<Notification>>([]);
,你就会让它工作。根据经验,除了对象之外的任何东西都使用 ref
,那是你想要使用 reactive
的时候。它比那更复杂,但如果你像这样使用它们,它总是有效的。
我正在尝试使用 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,我想知道我错过了什么。
reactive
不适用于数组。似乎是构图的限制api。您可以阅读类似的讨论 here.
使用 ref
而不是 reactive
,它应该可以正常工作。我已经构建了一些这样的应用程序并且可以确认它可以正常工作。
所以写:const state = ref<Array<Notification>>([]);
,你就会让它工作。根据经验,除了对象之外的任何东西都使用 ref
,那是你想要使用 reactive
的时候。它比那更复杂,但如果你像这样使用它们,它总是有效的。