Vue路由beforeEnter调用this.$store报undefined相关错误如何解决
错误原因
路由配置中的beforeEnter独享守卫的执行上下文没有绑定Vue实例,此处的this指向为undefined,因此无法通过this.$store访问Vuex/Pinia实例,触发属性读取报错。
解决方案
直接在路由文件中导入你的Store实例使用即可,修改步骤如下:
- 在
router/index.js文件头部导入项目的Store实例,导入路径根据你项目中Store的实际存放位置调整:
import store from '@/store'
- 修改
beforeEnter守卫中的代码,替换this.$store为导入的store实例,同时修正原逻辑的问题:原else分支中next(false)会阻止未登录用户进入登录页,改为next()放行即可。
修改后的完整路由配置如下:
{ path: '/', name: 'login', component: () => import( /* webpackChunkName: "hours" */ '../views/login.vue'), meta: { hideNavbar: true, }, beforeEnter: (to, from, next) => { if (store.state.authenticated.admin === true) { next('/home'); } else { next(); } } }
补充说明
如果你的项目使用Vue3 + Pinia,可直接在beforeEnter守卫中导入你定义的管理员状态相关store,直接调用实例获取状态即可,无需依赖this访问。
内容的提问来源于stack exchange,提问作者Maseeha Tasneem
相关产品推荐
相关产品推荐

