“getActivePinia()” was called but there was no active Pinia. Are you trying to use a store before calling “app.use(pinia)”?
See https://pinia.vuejs.org/core-concepts/outside-component-usage.html for help.
This will fail in production.
at useStore (pinia.js?v=e08caed9:1354:13)
at index.ts:80:19
根据提示可以大致了解是使用的时候还没有挂载pinia,看一下main.ts文件却发现已经是在挂载router前挂载了pinia。那便不是注册的问题,而是使用的时机问题。
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router/index";
import { createPinia } from "pinia";
const app = createApp(App);
const store = createPinia();
app.use(store);
app.use(router);
app.mount("#app");
我需要的是在路由前置守卫中,根据一些判断然后使用pinia中的action方法。一开始的写法是把pinia的仓库实例声明在路由守卫的外层作用域,方便使用。
import { useHeadStore } from "../store/head";
...
const headStore = useHeadStore();
...
router.beforeEach((to, from, next) => {next();
});
...
然后就报错了
最后解决办法是把 const headStore = useHeadStore(); 放到路由守卫的函数回调中声明,此时pinia肯定挂载成功了。于是代码变成了这样
import { useHeadStore } from "../store/head";
......
router.beforeEach((to, from, next) => {
const headStore = useHeadStore();
... 其余逻辑next();
});
...