本例是在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對象.