Vue Router 的导航守卫内部使用pinia | 报错getActivePinia was called with no active Pinia. Did you forget to install pinia?

运行环境

"pinia": "^2.0.28",
"vue": "^3.2.45",
"vue-router": "^4.1.6"

触发错误代码

import { createWebHistory, createRouter } from 'vue-router'
import useMenuStore from "@/store/modules/menu";

/* Layout */
import Layout from '@/layout'

// 公共路由
export const constantRoutes = [
    {
        path: "/:pathMatch(.*)*",
        component: () => import('@/views/error/404'),
    },
    {
        path: '/401',
        component: () => import('@/views/error/401'),
    },
    ...
]

const router = createRouter({
    history: createWebHistory(),
    routes: constantRoutes
});
const menuStore = useMenuStore();
//全局前置路由
router.beforeEach((to, from, next) => {
    menuStore.currentMenu = to.params["name"];
    next()
})

export default router;

此时浏览器控制台会报如下错误,这是因为 pinia 还没有挂载到 app 上。

解决办法
pinia官网
pinia 官网已经清楚写明组件外应该如何使用 pinia:

在钩子函数外,pinia 还没有被挂载,但是在前置守卫函数中,pinia 已经被挂载了,所以获取全局状态,需要在钩子函数中进行,正确的实现如下:

// const menuStore = useMenuStore();
// 全局前置路由
router.beforeEach((to, from, next) => {
    const menuStore = useMenuStore();
    menuStore.currentMenu = to.params["name"];
    next()
})
posted @ 2023-01-28 02:20  槑孒  阅读(711)  评论(0编辑  收藏  举报