简体   繁体   English

登录后无法重定向?

[英]Can't redirect after login?

Getting a TypeError: Cannot read property '$router' of undefined when trying to redirect after login.获取TypeError: Cannot read property '$router' of undefined I have tried various methods on the router instance but it is undefined according to the console?我在路由器实例上尝试了各种方法,但根据控制台未定义?

Login action (inside store):登录操作(店内):

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);
    });
},

You just need to preserve this before calling it again inside .then(...) like:您只需要在.then(...)中再次调用this之前保留它,例如:

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));
},

Your problem is that you use this inside an regular function, that means that this is binded to the function and not the vue instance, change it to an arrow function:您的问题是您在常规 function 中使用thisthis意味着它绑定到 function 而不是 vue 实例,将其更改为箭头 ZC1C425268E68385D1AB5074C17A9:

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

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

Other solution is to .bind() it:其他解决方案是.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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM