解決js函數閉包中this指針指向變化而導致this.$router.push不起作用的問題
譬如,在使用axios進行數據請求時,如下所示:
this.axios
.post(url, params, config)
.then(function(response) {
// 成功
if (response.data.error_code == 0) {
this.$router.push({ path: "/" });
}
})
.catch(function(error) {
this.$message.error(error);
});
在.then()
中包含了一個匿名函數,此時this
指針指向已經改變,this.$router.push()
是不起作用的,解決辦法是在進行axios請求前緩存this指針,如下所示:
var self = this;
this.axios
.post(url, params, config)
.then(function(response) {
// 成功
if (response.data.error_code == 0) {
self.$router.push({ path: "/" });
}
})
.catch(function(error) {
self.$message.error(error);
});
其它類似的this指針指向改變的問題也可參照上述解決方法。