在 VueJS 中使用 Axios - 这个未定义 [英] Using Axios in VueJS - this undefined

查看:14
本文介绍了在 VueJS 中使用 Axios - 这个未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 typescript 和 vuejs + axios,我在 post 请求中有以下 .catch 函数 - 我试图捕获一些网络错误并向最终用户报告状态:

 .catch(function(error) {控制台错误(错误响应);if ( error.message === "网络错误" ) {this.alert.show = 1;this.alert.message = error.message + ': 请稍后再试';}});

this.alert.show 在调试器中抛出未定义的this".这通常是 javascript/typescript 和异常处理程序的问题,还是 Axios 中的错误或我找不到文档的设计决策?

如果没有this"引用,我有没有办法将其传达回我的组件?

完整块:

出口默认{数据() {返回 {形式: {电子邮件: '',密码: '',},警报: {显示:0,信息: '',},};},方法: {onSubmit(evt) {evt.preventDefault();如果(this.form.password.length > 0){//TODO:.catch() 的可怕解决方法.让那个=这个;this.$http.post('http://localhost:3000/login', {电子邮件:this.form.email,密码:this.form.password,}).then((响应) => {const is_admin = response.data.user.is_admin;localStorage.setItem('user', JSON.stringify(response.data.user));localStorage.setItem('jwt', response.data.token);if (localStorage.getItem('jwt') != null) {this.$emit('登录');如果 (this.$route.params.nextUrl != null) {this.$router.push(this.$route.params.nextUrl);} 别的 {如果(is_admin === 1){this.$router.push('admin');} 别的 {this.$router.push('仪表板');}}}}).catch((错误) => {控制台错误(错误);if ( error.message === '网络错误' ) {this.alert.show = 10;this.alert.message = error.message + ': 请稍后再试';}});}},onReset(evt) {evt.preventDefault();/* 重置我们的表单值 */this.form.email = '';this.form.password = '';/* 重置/清除原生浏览器表单验证状态的技巧 */this.show = false;this.$nextTick(() => { this.show = true; });},},};

Vue 模板(Login.vue):