解決js函數閉包中this指針指向變化而導致this.$router.push不起作用的問題

解決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指針指向改變的問題也可參照上述解決方法。

發佈了62 篇原創文章 · 獲贊 12 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章