vue2:路由前置守卫无法获取到this.$store.state.xxx

在获取到vuex的数据时候,想在router目录下的index.js文件去获取到vuex仓库中声明的全局变量,但是通过this.$store.stote.xxx去获取的时候,报错提示:$store未定义

一、store/index.js
const store = new Vuex.Store({
  state: {
    // 属性:属性值
    LoginState: 0,
    userInfo: { // 用户信息
      userName: '张三'
    }
  }

(这里的数据只做举例)

二、router/index.js
router.beforeEach((to, from, next) => {
  // 获取到用户名信息
  const loginState = this.$store.state.userInfo.userName
  console.log(loginState)
  // next()
})

提示报错

三、解决方法

参考文档:vue2中,在路由守卫中this.$store获取vuex失败问题的解决(vue小技巧)(vue面试必会知识点) - 掘金 (juejin.cn)

其实也就是,导入vuex的仓库,然后用vuex去代替this.$store

1、在router/index.js顶部导入

import vuex from '@/store/index.js'

2、用vuex.state.xxx 代替 this.$store.state.xxx

  const loginState = vuex.state.userInfo.userName
  console.log(loginState)

猜你喜欢

转载自blog.csdn.net/qq_63141957/article/details/134145782