外部js调用pinia时,解决报错getActivePinia was called with no active Pinia. Did you forget to install pinia?
外部js调用pinia时,解决报错getActivePinia was called with no active Pinia. Did you forget to install pinia?
·
问题:vue3+vue-router4,在router中使用pinia状态管理,获取store中存储的菜单数据,好在beforeEach中判断权限。不料报错getActivePinia was called with no active Pinia. Did you forget to install pinia?
原因:是pinia在main.ts中还未注册好,便在其他文件中使用了它。
解决前已有的store相关代码,如loginStore.ts:
import { defineStore } from "pinia";
const loginStore = defineStore("login", {
state: () => {
return {
userInfo: {},
menus: [],
roles: [],
};
},
getters: {
getUserInfo(state) {
return state.userInfo;
},
},
actions: {
setRole(data: any) {
this.roles = data;
},
setMenu(data: any) {
this.menus = data;
},
},
});
export default loginStore;
解决方案
在store目录中单独创建一个store.ts:
import { createPinia } from 'pinia';
const pinia = createPinia();
export default pinia;
接着在main.ts 引入该文件,用来注册pinia:
// xxxxx省略无关代码xxxxxxx
import pinia from "@/store/store"
app.use(pinia)
// xxxxx省略无关代码xxxxxxx
router等其他外部js中使用时,需要重新导入创建pinia实例才行:
import pinia from '@/store/store'
import { loginStore} from "@/store/loginStore"
const store = loginStore(pinia)
// store可以在本文件中随意使用
console.log(store)
更多推荐
已为社区贡献6条内容
所有评论(0)