關於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博客






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM