wx.createSelectorQuery()异步问题?研究两天了。求大佬说一下
wxml代码:
<scroll-view scroll-x="true" scroll-with-animation class="horizontal" scroll-left="{{scroll}}" id="horizontal">
<view class="tabs">
<view class="tab {{active==index?'activeTab':''}}" wx:for="{{list}}" wx:key="index" bindtap="getItem" data-index="{{index}}" id="item-{{index}}">{{item.name}}</view>
<view class='line' id="line" style="left:{{list[active].offsetLeft}}px;width:{{list[active].width}}px;"></view>
</view>
</scroll-view>
js部分
data: {
list: [{
id: "0",
name: "测试"
},
{
id: "0",
name: "测试测试"
},
{
id: "0",
name: "测试测试测试"
},
],
}
传入list给list增加offsetLeft和width属性
initItem(e) {
return new Promise((resolve, reject) => {
e.forEach((item, index) => {
let view = wx.createSelectorQuery().select("#item-" + index)
view.boundingClientRect(res => {
item.offsetLeft = res.left
item.width = res.width
}).exec()
})
resolve(e)
})
},
在生命周期onReady初始化打印res可以,res[0]就不行,昨天我问了下是异步问题,所以加了promise,但是.then还是打印res[0]为未定义。求大佬解决
万分感谢
this.initItem(this.data.list).then(res=>{
console.log(res)
console.log(res[0])
})