【发布时间】:2021-10-22 12:41:17
【问题描述】:
在我的 vue 项目中,我需要检查每条路线的 jwt 令牌,因此在 beforeEach 方法中,如果 jwt 令牌未保存在 localStorage 中,我将向后端发送请求。这是我来自src/router/index.js的代码:
router.beforeEach((to, from, next) => {
if (to.meta.authRequired) {
const jwt = localStorage.getItem('jwt');
if (!jwt) {
this.$axios.get(`/api/users/jwtWithoutLogin`,{
}).then((response) => {
localStorage.setItem('jwt', response.data.jwt)
});
}
const payload = JSON.parse(atob(jwt.split('.')[1]));
const username = payload.username
console.log(username)
localStorage.setItem("username", username)
}
next();
});
但是在浏览器的控制台中我总是出错:
TypeError: _this is undefined
我尝试使用选项self 而不是this,我尝试不使用this,但它不起作用。我也在考虑在 beforeEach 方法中删除这个 axios 调用,但我不知道每次页面加载时我还能把它放在哪里调用?
【问题讨论】:
标签: vue.js axios this vue-router