關於vue中使用ajax頁面不更新問題

使用背景:

    改變的內容: 

treeListOne: []

  使用ajax來更新data屬性,發現頁面沒更新,例子如:

            

$.ajax({
url: '/api/get_biz_inst_topo/',
type: 'post',
dataType: 'json',
data: JSON.stringify({bk_biz_id: this.bus_val}),
success: function (response) {
if (response.status === true) {
console.log(response.data);
// this.treeListOne = JSON.parse(JSON.stringify(response.data));
//this.treeListOne = [];
console.log(this)
//this.treeListOne = JSON.stringify(response.data)
this.treeListOne = JSON.stringify(response.data)
console.log(this.treeListOne)
}
},
error: function (data) {
console.log(data)
}
})

發現頁面沒更新,treeListOne 好像變了,其實你打印ajax裏的this會發現這值怎麼是個字符串?

其實問題就是這裏的this就是指向ajax,而不是vue,所以這裏對數據不會產生變動。

解決:
1、可以用axios(雙箭頭), 這個指向vue本身,可以對data屬性進行賦值。
axios({
url: "/api/get_biz_inst_topo/",
method: 'post',
responseType: 'json', // 默認的
data: JSON.stringify({bk_biz_id: this.bus_val}),
}).then(res => {
if (res.data.status) {
console.log(res.data.data)
console.log(this)
this.treeListOne = res.data.data
}
})


2、ajax或axios 外層加個var變量,如
var that = this
$.ajax({
url: '/api/get_biz_inst_topo/',
type: 'post',
dataType: 'json',
data: JSON.stringify({bk_biz_id: this.bus_val}),
success: function (response) {
if (response.status === true) {
console.log(response.data);
// this.treeListOne = JSON.parse(JSON.stringify(response.data));
//this.treeListOne = [];
console.log(this)
//this.treeListOne = JSON.stringify(response.data)
that.treeListOne = response.data

}
},
error: function (data) {
console.log(data)
}
})

參照:Vue使用ajax或者axios獲取數據,能獲取到數據但是頁面沒有更新_weixin_55560445的博客-CSDN博客





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章