在vue2引入pinia,写起来比vuex要爽,但是当你在路由拦截的时候需要用到pinia的一些数据作为支撑来决定你跳转的路由很可能会遇到下面的情况。
官网没说清楚的坑:Migrating from Vuex ≤4 | Pinia
解读:
文章说的,在路由里使用pinia时,直接在beforeEach里使用就好了
// Pinia的例子
import { useAuthUserStore } from '@/stores/auth-user'
router.beforeEach((to, from, next) => {
// Must be used within the function!
const authUserStore = useAuthUserStore()
if (authUserStore.loggedIn) next()
else next('/login')
})
按照官网的例子,我们分分钟在打开页面的时候就会收到这么一个报错;
这是因为在路由加载的时候,pinia还没完成install,所以无法识别beforeEach中使用的store内容;
——————————————————手动分割线————————————————————
解决方法:
定义pinia实例
/* store.js - 创建统一的pinia实例 */
import { createPinia } from 'pinia'
const pinia = createPinia()
export default pinia
在路由使用时,需要引入pinia实例
/* uue-router 中使用 */
import router from './router' //引入做好配置的router实例
import { UserStore } from '@/pinia/user'
import pinia from '@/pinia' //引入pinia实例
router.beforeEach((to, from, next) => {
//在外面声明会导致在未装载pinia就完成了初始化 导致取值失败
const userStore = UserStore(pinia)
const userId = userStore.$state.userId
})
仅定义路由的普通对象
***
***
const router = {
routes: [], // 你的路由表
mode: 'history', // 你的模式
beforeEach: (to, from ,next) => {
const store = useMyStore();
*** 你的逻辑代码***
next();
},
afterEach: () => {
*** 你的逻辑代码 ***
},
}
export default router;
然后在main中要确保优先use pinia;
****
****
import router from '@/router';
improt {createPinia, PiniaVuePlugin} from 'pinia';
import Router from 'vue-router';
Vue.use(PiniaVuePlugin);
const pinia = createPinia();
Vue.use(Router);
new Vue({
***
pinia,
router: new Router(router),
***
}).$mount('#app');
以上就能正常的运行项目了。