【发布时间】:2022-01-11 11:00:50
【问题描述】:
$新年快乐!因此,我在获取身份验证令牌后设置了重定向,并且在控制台中不断收到“TypeError: Cannot read properties of undefined (reading '$router')”,并且用户没有被重定向到所需的页面(“/仪表盘”)。我将身份验证外包给 dataRequests.user.js 文件,然后转到 vue 组件。提前致谢。代码如下:
import common from "./dataRequests.commons";
import { login, inputLogin, inputPassword } from '/src/pages/Index.vue'
let userRequest = {}
userRequest.authenticate = (inputLogin, inputPassword) => {
return new Promise(() => {
let axios = require("axios");
let config = {
method: 'post',
baseURL: common.baseURL + '/auth/login',
headers: {
'Content-Type': 'application/json',
},
data : {
login: inputLogin,
password: inputPassword,
}
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.then(() => this.$router.push(this.$router.redirect || '/dashboard'))
.catch(function (error) {
console.log(error);
//console.log('input login', this.inputLogin)
//console.log('input password', this.inputPassword)
});
console.log('input login', inputLogin)
console.log('input password', inputPassword)
});
}
export default userRequest;
【问题讨论】:
-
为什么你认为
this.$router应该指路由器?你觉得this会在这里指什么……? -
我是 vue 新手,所以我不太明白这是什么。是为了打电话(除了有问题的路线,就像我想的其他语言中的“自我”)。这只是我在网上找到的语法,它在 vue 组件中有效。我不明白为什么当我外包 auth 功能时它不起作用。我试过没有它,但我仍然得到一个错误,除了它标记“ReferenceError: $router is not defined”。
-
感谢您的回复。我想出了一个解决方法(我忘了说我也在使用 Quasar.js):显然 vue.js 不喜欢在 .vue 组件之外使用 vue 路由器(至少不搞乱路由器/ routes.js),所以,我在 .vue 组件和 dataRequests.js 文件之间做了一个类似循环的循环。我首先在 setup() 中将字段作为导出作为输入 ref() 发送,在 dataRequests 中导入它们,在其中执行承诺,然后将结果导出到 .vue 组件并在 部分。
标签: vue.js redirect error-handling router