我需要在axios調用後立即更新我的變量this.xCtesPorRuta,這樣我才能從數據庫中顯示一些信息,例如select。 axios調用通過按鈕的v-on:click事件激活。如何在axios呼叫後立即更新Vue?
我將axios響應存儲在變量上,但它不會立即更改,只有在單擊另一個元素時纔會這樣做。我試圖用nexttick強制更新,但沒有成功。
第一次嘗試:
var request = {rutas:this.xRutasSeleccionadas , tipos:this.xTipos}
axios.post('/querys/', request).then(response => this.xCtesPorRuta = response.data)
this.$nextTick(function() {
this.$forceUpdate();
});
我知道Vue公司有問題的更新陣列瞬間,但我以前管理使用拼接方法,其次是nextTick/forceUpdate的黑客攻擊,迫使陣列的變化。從未在axios之後通過。
編輯:我在這裏錯誤地使用了this
。感謝@Demonyowh和@fracz的幫助。
第二次嘗試。結果是一樣的第一個學嘗試:
var myVar = this;
var request = {rutas:this.xRutasSeleccionadas , tipos:this.xTipos}
axios.post('/querys/', request).then(function (response) {
myVar.xCtesPorRuta = [];
for (var i=0; i<response.data.length; i++) {
myVar.xCtesPorRuta.splice(i, 1, response.data[i]);
}
})
this.$nextTick(function() {
this.$forceUpdate();
});
原來使用splice
沒有幫助這個時候。
https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work – fracz
謝謝你,我對自己的代碼做了各自的修改,並編輯修復'this'問題的問題。 – Adocad
1.您可以避免使用箭頭'=>'函數創建另一個變量,該函數不會綁定您的'this'範圍。 2.除非使用圖書館,否則這種未處理的拒絕將被注意,你應該「抓住」迴應。 3.您的'$ nextTick'調用在獲得響應之前調用,爲什麼? [異步vs同步](https://stackoverflow.com/questions/16336367/what-is-the-difference-between-synchronous-and-asynchronous-programming-in-node) – Chay22