vue3+pinia+ts开发时,报错[🍍]: “getActivePinia()” was called but there was no active Pinia. Did you forget to install pinia? const pinia = createPinia(),解决办法
- vue3开发
- 2023-07-17
- 363热度
- 0评论
-
首先确保安装了pinia的基础上,创建src/store/index.ts
import { createPinia } from "pinia"; // 创建 Pinia Store const pinia = createPinia(); //对外暴露出去 export default pinia;
-
然后在main.ts中引入并挂载pinia
import { createApp } from "vue"; //引入pinia import pinia from "./store"; ...... const app = createApp(App); app.use(pinia).mount("#app");
-
在src/store/modules/xxx.ts新建相应模块
//创建用户存储相关 import { defineStore } from "pinia"; //引入接口 import { login } from "@/api/user"; //引入数据类型 import type { loginForm } from "@/api/user/type"; //引入notification import { ElNotification } from "element-plus"; import { setItem, getItem } from "@/utils/storage"; const useUserStore = defineStore("User", { //存储数据的地方 state: () => { return { token: getItem("token") || "", }; }, //异步逻辑处理的地方 actions: { //处理用户登录的方法 async userLogin(data: loginForm) { let result = await login(data); //将token存储到本地 if (result.code === 200) { setItem("token", result.data.token); ElNotification({ title: "登录成功", message: `欢迎回来,${data.username}`, type: "success", }); } else { //如果登录失败,错误提示 ElNotification({ title: "登录失败", message: `${result.message}`, type: "error", }); } }, }, getters: {}, }); //对外暴露 export default useUserStore;
-
在组件中引入
import useUserStore from '@/store' const userStore = useUserStore()
使用nextTick解决上述报错
// 使用nextTick函数确保在Vue应用实例完全初始化后再调用useStore函数
nextTick(() => {
const store = useStore()
// 在这里可以继续处理store
})
import router from '@/router'
import useUserStore from '@/store/modules/user'
import { nextTick } from 'vue'
//白名单
const whiteList: string[] = ['/login']
/**
* 路由导航守卫
*/
router.beforeEach(async (to, from, next) => {
nextTick(() => {
const userStore = useUserStore();
//获取token
const token = userStore.$state.token
//判断是否有token
if (token) {
console.log('to.path-->>',to.path);
//判断是否去登录页,用户已登录,则不允许进入login
if (to.path === '/login') {
//去首页
next()
} else {
next()
}
} else {
//没有token
if (whiteList.indexOf(to.path) !== -1) {
//白名单
next()
} else {
//去登录页
next('/login')
}
}
})
})