Vue 请求无法获取组件数据



当HTTP请求返回错误时,我正在尝试禁用加载,但它给了我此错误。

捕获(在承诺中(类型错误:无法设置未定义的属性"加载">

法典

export default {
name: 'login',
data() {
return {
loading: false, //can't be set to false on request error
}
},
methods: {
login: function () {
this.loading = true;
const { username, password } = this
this.$store.dispatch('login', { username, password }).then((resp) => {
setTimeout(() => {
this.loading = false;
}, 5000);
// this.$router.push({name: 'dashboard'})
}).catch(function (error) {
this.loading = false; // Uncaught (in promise) TypeError: Cannot set property 'loading' of undefined
console.log('error', error);
});
}
}
}

知道吗?

this表示在 catch 方法中调用函数的对象,而不是当前的 vue 组件。

因此,您可以在外面使用var vm=this并在下面使用之后使用。

login: function () {
this.loading = true;
var vm = this;
.....
.....
}).catch(function (error) {
vm.loading = false;
console.log('error', error);
});
}

或使用箭头方法

login: function () {
.....
.....
}).catch((error) => {
this.loading = false;
console.log('error', error);
});
}

您已经在下面的代码中使用了带有setTimeout的箭头方法,所以我想您知道这一点,只需使用它来解决此问题

setTimeout(() => {
this.loading = false;
}, 5000);

最新更新