繁体   English   中英

登录后无法重定向?

[英]Can't redirect after login?

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

您只需要在.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));
},

您的问题是您在常规 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
    })

其他解决方案是.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