Не удается перенаправить после входа в систему?

Получение 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);
    });
},

2 ответа

Решение

Вам просто нужно сохранить 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));
},

Ваша проблема в том, что вы используете 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))
Другие вопросы по тегам