vue2中,在路由守卫中this.$store获取vuex失败问题的解决(vue小技巧)(vue面试必会知识点)

3,712 阅读1分钟

我们通常在vue中获取vuex中的数据,使用的是this.$store的方式来获取,但是在vue-router的路由守卫中,this并不是指向vue实例的,这个时候我们就需要变通一下了,例如,在main.js中,使用路由守卫,并在路由守卫中获取vuex中的数据可以像下图这样: 1.import vuex的实例。

import vuex from './store/index';

2.在路由守卫中使用import进来的vuex实例.state的方式获取到vuex中的数据:

router.beforeEach( (to, from, next) => {
    if(from.path === '/preview'){
    // vuex.state === this.$store.state
        console.log(vuex.state.stage)
    next()
})

这样就可以在路由守卫中获取到vuex的值了。