[英]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 中使用this
, this
意味着它綁定到 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.