无法读取未定义的属性"$router"



I’对给定的代码有问题,

submit () {
fetch(this.url + "/auth/login",{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
mobilenumber: this.form.mobilenumber,
password: this.form.password})
}).then(function (response) {
console.log("Response = " + response.status);
if (response.status == 200) {
this.$router.push({
name: "Users",
})
} else {
alert("Not logged in");
}
return response.json();
}).then(function (data) {

}).catch(function (error) {
console.log("-------- error ------- " + error);  
});
}

当调用submit函数时,我想导航到"用户"页面。我为此写了this.$router.push({ name: "Users" })。但我在控制台中出现错误:

Cannot read property '$router' of undefined.

我试过self.$router.push({ name: "Users" })。尽管如此,我还是在控制台中遇到了同样的错误。请帮忙。

您需要对外部作用域的引用,因为在提取回调中this是未定义的。为了解决这个问题,您可以通过创建一个引用作为来创建外部范围的引用

submit () {
let self = this;
...

然后,您可以使用作为参考

self.$router.push({
name: "Users",
})

相关内容

最新更新