使用打字稿和vuejs + axios,我在发布请求时具有以下.catch函数-我正试图捕获一些网络错误并向最终用户报告状态:
.catch(function(error) {
console.error(error.response);
if ( error.message === "Network Error" ) {
this.alert.show = 1;
this.alert.message = error.message + ': Please try again later';
}
});
this.alert.show会在调试器中抛出未定义的“ this”。这通常是javascript / typescript和异常处理程序的问题,还是Axios中的错误或我找不到相关文档的设计决策?
在没有“ this”引用的情况下,是否有办法将其传达回我的组件?
完整块:
export default {
data() {
return {
form: {
email: '',
password: '',
},
alert: {
show: 0,
message: '',
},
};
},
methods: {
onSubmit(evt) {
evt.preventDefault();
if (this.form.password.length > 0) {
// TODO: Hideous workaround for .catch().
let that = this;
this.$http.post('http://localhost:3000/login', {
email: this.form.email,
password: this.form.password,
})
.then((response) => {
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('loggedIn');
if (this.$route.params.nextUrl != null) {
this.$router.push(this.$route.params.nextUrl);
} else {
if (is_admin === 1) {
this.$router.push('admin');
} else {
this.$router.push('dashboard');
}
}
}
})
.catch((error) => {
console.error(error);
if ( error.message === 'Network Error' ) {
this.alert.show = 10;
this.alert.message = error.message + ': Please try again later';
}
});
}
},
onReset(evt) {
evt.preventDefault();
/* Reset our form values */
this.form.email = '';
this.form.password = '';
/* Trick to reset/clear native browser form validation state */
this.show = false;
this.$nextTick(() => { this.show = true; });
},
},
};
Vue模板(Login.vue):
<template>
<div>
<b-container class="loginPage">
<b-row>
<b-col sm="4"/>
<b-col sm="4">
<b-form @submit="onSubmit" @reset="onReset">
<h2>Login</h2>
<p>Please enter your email and password</p>
<b-form-input id="exampleInput1"
type="email"
v-model="form.email"
required
placeholder="Enter email">
</b-form-input>
<b-form-input id="exampleInput2"
type="password"
v-model="form.password"
required
placeholder="Enter password">
</b-form-input>
</b-form-group>
<div class="forgot">
<a href="reset.html">Forgot password?</a>
</div>
<b-button class="btn-primary" type="submit" variant="primary">Submit</b-button>
<b-button class="btn-reset" type="reset" variant="danger">Reset</b-button>
<b-alert :show="alert.show" variant="danger">
{{alert.message}}
</b-alert>
</b-form>
</b-col>
<b-col sm="4"/>
</b-row>
</b-container >
</div>
</template>
答案 0 :(得分:5)
您正在创建一个新的本地函数作用域。请改用粗箭头。
.catch((error) => {
console.error(error.response);
if ( error.message === "Network Error" ) {
this.alert.show = 1;
this.alert.message = error.message + ': Please try again later';
}
});
答案 1 :(得分:1)
您还可以将this
分配给全局变量并在回调中访问它:
let that =this;
...
.catch((error) => {
console.error(error.response);
if ( error.message === "Network Error" ) {
that.alert.show = 1;
that.alert.message = error.message + ': Please try again later';
}
});