[英]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 的限制。 您可以在此處閱讀類似的討論。
使用ref
而不是reactive
,它應該可以正常工作。 我已經構建了一些這樣的應用程序,並且可以確認它工作正常。 所以寫: const state = ref<Array<Notification>>([]);
,您將可以使用它。 根據經驗,除了對象之外的任何東西都使用ref
,那就是你想要使用reactive
。 它比這更復雜,但如果您像這樣使用它們,它將始終有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.