在 VueJS 中使用 Axios - 这个未定义 [英] Using Axios in VueJS - this undefined
问题描述
使用 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):
<div><b-container class="loginPage"><b行><b-col sm="4"/><b-col sm="4"><b-form @submit="onSubmit" @reset="onReset"><h2>登录</h2><p>请输入您的电子邮件和密码</p><b-form-input id="exampleInput1"类型=电子邮件"v-model="form.email"必需的placeholder="输入电子邮件"></b-form-input><b-form-input id="exampleInput2"类型=密码"v-model="form.password"必需的placeholder="输入密码"></b-form-input></b-form-group><div class="忘记了"><a href="reset.html">忘记密码?</a>
<b-button class="btn-primary" type="submit" variant="primary">提交</b-button><b-button class="btn-reset" type="reset" variant="danger">重置</b-button><b-alert :show="alert.show" variant="danger">{{alert.message}}</b-警报></b-form></b-col><b-col sm="4"/></b-row></b-容器>
模板>
也使用 https://bootstrap-vue.js.org.
您正在创建一个新的本地函数作用域.改用粗箭头.
.catch((error) => {控制台错误(错误响应);if ( error.message === "网络错误" ) {this.alert.show = 1;this.alert.message = error.message + ': 请稍后再试';}});
Using typescript and vuejs + axios, i have the following .catch function on a post request - I'm attempting to trap some network errors and report status to the end user:
.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 throws "this" undefined in the debugger. Is this a problem with javascript/typescript and exception handlers in general, or is this a bug in Axios or a design decision I can't find documentation for?
And is there a way for me to communicate this back to my component absent a "this" reference?
Full block:
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 template (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>
Also using https://bootstrap-vue.js.org.
You're creating a new local function scope. Use fat arrow instead.
.catch((error) => {
console.error(error.response);
if ( error.message === "Network Error" ) {
this.alert.show = 1;
this.alert.message = error.message + ': Please try again later';
}
});
这篇关于在 VueJS 中使用 Axios - 这个未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!