vue3中pinia中的数组push添加元素时报错(已实战)
如图所示,tabStore.tabList.push方法报错

这个错误是因为 tabStore中的tabList在使用时变成了 Proxy 对象且失去了数组方法。我们需要修改 store 的定义方式,确保 tabList 始终是一个数组。让我们修改 tabStore:
import { defineStore } from "pinia";
export const useTabStore = defineStore("tabs", {
state: () => ({
activeIndex: "",
tabList: [], //存放tab标签页的数组,只接收固定格式对象的标签页数组[{name, title, content}]
badge: 10 //顶部导航栏未读消息
}),
actions: {
// 清空所有标签页数据
clearAllTabs() {
this.tabList = [];
this.activeIndex = "";
},
// 添加标签页的方法
addTabItem(tabObj) {
if (!this.tabList) {
this.tabList = [];
}
// 检查是否已存在相同路径的标签页
if (!this.tabList.some(tab => tab.content === tabObj.content)) {
this.tabList = [...this.tabList, tabObj];
}
}
},
persist: {
enabled: true,
strategies: [{
key: 'tabs',
storage: localStorage,
}]
}
});
然后在 index.vue 中修改 addTab 方法的实现:
const addTab = (targetName, path) => { // 参数有效性校验 if (!targetName || !path) return; tabIndex += 1; const tabObj = { title: targetName, name: String(tabIndex), content: path, }; // 使用 store 中的方法添加标签页 tabStore.addTabItem(tabObj); tabStore.activeIndex = String(tabIndex); console.log("初始化加载时的tabStore.activeIndex:", tabStore.activeIndex); };
修改说明:
1. 在 store 中添加了专门的 `addTabItem` action 来处理标签页的添加
2. 使用展开运算符创建新数组来更新 tabList,这样可以确保响应性
3. 移除了重复的 push 操作
4. 添加了对 tabList 是否存在的检查
这样修改后应该可以解决 `push is not a function` 的错误,同时保持了标签页添加的功能完整性。错误的原因是直接操作 Proxy 对象可能会导致数组方法丢失,通过在 store 中定义专门的 action 来处理数组操作可以避免这个问题。

浙公网安备 33010602011771号