1

TypeError: Cannot read property '$router' of undefined登录后尝试重定向时得到一个。我在路由器实例上尝试了各种方法,但根据控制台未定义?

登录操作(店内):

login({ commit, dispatch }, { username, password }) {
    const querystring = require('querystring');

    this.$axios.$post('connect/token', querystring.stringify({
        client_id: process.env.CLIENT_ID,
        client_secret: process.env.CLIENT_SECRET,
        username,
        password,
        grant_type: 'password'
    }))
    .then(function (response) {
        dispatch('setToken', { 
            token: response.access_token, 
            expiresIn: response.expires_in 
        });

        this.$router.push({name: 'home' }); // this line is the issue
    })
    .catch(errors => {
      console.dir(errors);
    });
},
4

2 回答 2

1

您只需要this在内部再次调用它之前保留它.then(...)

login({ commit, dispatch }, { username, password }) {

    // Store `this` inside variable vm here
    const vm = this;
    const querystring = require('querystring');

    vm.$axios.$post('connect/token', querystring.stringify({
        client_id: process.env.CLIENT_ID,
        client_secret: process.env.CLIENT_SECRET,
        username,
        password,
        grant_type: 'password'
    }))
    .then(function (response) {
        dispatch('setToken', { 
            token: response.access_token, 
            expiresIn: response.expires_in 
        });

        // Use this for debugging purpose only
        console.log( vm.$router )

        // You can now access `$router` safely here now
        vm.$router.push({name: 'home' });
    })
    .catch(errors => console.dir(errors));
},
于 2020-06-02T13:49:36.720 回答
0

您的问题是您this在常规函数中使用,这意味着this绑定到函数而不是 vue 实例,将其更改为箭头函数:

.then((response) => {
        dispatch('setToken', { 
            token: response.access_token, 
            expiresIn: response.expires_in 
        });

        this.$router.push({name: 'home' }); // this line is the issue
    })

其他解决方案是.bind()

.then(function (response) {
        dispatch('setToken', { 
            token: response.access_token, 
            expiresIn: response.expires_in 
        });

        this.$router.push({name: 'home' }); // this line is the issue
    }.bind(this))
于 2020-06-02T13:50:16.303 回答