本例是在VUE + ELEMENT-UI的环境中,在javascrpit的promise中调用完接口,在then中要调用element-ui的消息提示框.刚开始是这样写的:
onSubmit() { instance .post( `http://localhost:8989/user/regist/${this.verifyCode}/${this.key}`, this.user ) .then(function(response){ console.log(this); if (response.data.code === 200) { this.$alert("点击跳转到登录页面", "注册成功", { confirmButtonText: "确定", callback: action => { this.$message({ type: "info", message: `action: ${action}` }); } }); } else { this.$message({ message: response.data.msg, type: "error" }); } }) .catch(function(error) { console.log(error); this.$message.error(error); }); },
这样在红色代码处的this是undefined.
但是将代码中绿色代码中的函数定义换成箭头函数,红色代码处就可以访问this了,而且这个this就是,顶层的VUE对象.