报错信息
"XXX" was called but there was no active Pinia. Did you forget to install
报错截图
原因分析
- 函数的调用发生在pinia注入之前
解决方法(搬运自pinia官网)
原理说明
- Pinia store 依靠
pinia实例在所有调用中共享同一个 store 实例。大多数时候,只需调用你定义的useStore()函数,完全开箱即用。例如,在setup()中,你不需要再做任何事情。但在组件之外,情况就有点不同了。 实际上,useStore()给你的app自动注入了pinia实例。这意味着,如果pinia实例不能自动注入,你必须手动提供给useStore()函数。 你可以根据不同的应用,以不同的方式解决这个问题。
案例
import { createRouter } from 'vue-router'
const router = createRouter({
// ...
})
// ❌ 由于引入顺序的问题,这将失败
const store = useStore()
router.beforeEach((to, from, next) => {
// 我们想要在这里使用 store
if (store.isLoggedIn) next()
else next('/login')
})
router.beforeEach((to) => {
// ✅ 这样做是可行的,因为路由器是在其被安装之后开始导航的,
// 而此时 Pinia 也已经被安装。
const store = useStore()
if (to.meta.requiresAuth && !store.isLoggedIn) return '/login'
})
解决方式
- 即:将使用store的位置调整到pinia注册之后