問題描述:在uniapp中使用uni.request獲取后端數(shù)據(jù)并渲染,但是獲取到了數(shù)據(jù)無法進(jìn)行全局賦值。文章來源:http://www.zghlxwxcb.cn/news/detail-523222.html
data() {
return {
array:[]
};
},
onLoad() {
this.updateData();
}
updateData(){
uni.request({
url:'*****',
data:{},
header:{'Content-Type':'application/x-www-form-urlencoded'},
success:(res)=>{
console.log(res)
let data = res.data;
this.array = data; // 在此步可以獲取到數(shù)據(jù)
},
fail: () => {
uni.showToast({
icon: 'none',
title: '網(wǎng)絡(luò)異常,請(qǐng)稍后重試'
});
}
});
this.useData(); // 調(diào)用方法
}
}
useData(){
console.log(this.array); // 在此步獲取到的數(shù)據(jù)為初始數(shù)據(jù)
}
- 造成數(shù)據(jù)無法全局賦值的原因主要是:uni.request是異步請(qǐng)求,此時(shí)打印出來的值,其執(zhí)行機(jī)制是:useData方法再到uni.request。
- 如果需要調(diào)用函數(shù)并渲染到全局,則需要在更改方法的放置位置。
updateData(){
uni.request({
url:'*****',
data:{},
header:{'Content-Type':'application/x-www-form-urlencoded'},
success:(res)=>{
console.log(res)
let data = res.data;
this.array = data; // 在此步可以獲取到數(shù)據(jù)
this.useData(); // 在異步進(jìn)行調(diào)用方法
},
fail: () => {
uni.showToast({
icon: 'none',
title: '網(wǎng)絡(luò)異常,請(qǐng)稍后重試'
});
}
});
}
}
附:箭頭函數(shù)指向問題文章來源地址http://www.zghlxwxcb.cn/news/detail-523222.html
- 使用this直接賦值的方法
uni.request({
...
success: (res) => {
this.data = res.data; //若使用箭頭函數(shù)則可以進(jìn)行賦值
},
fail: (err) => {
console.error(err);
},
});
- 使用that來間接賦值的方法
let that = this;
uni.request({
...
success: function(res){
that.data = res.data; //使用that來間接賦值
},
...
});
- 解釋:如果success直接寫成普通函數(shù)的形式,打印出來的this是success函數(shù)自身。而將success修改為箭頭函數(shù)即可拿到Vue實(shí)例對(duì)象的數(shù)據(jù)并進(jìn)行賦值及渲染到頁面上。
- 區(qū)分:如果是箭頭函數(shù),this的指向是上下文作用域,不可能指向?qū)ο螅?strong>如果是普通函數(shù)或方法,this指向上一個(gè)作用域的this或者調(diào)用這個(gè)方法的對(duì)象。
到了這里,關(guān)于uniapp使用uni.request獲取后端數(shù)據(jù)并渲染 | 含如何處理獲取到數(shù)據(jù)無法渲染問題的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!