现在有个需求是点击列表的评论按钮,进入详情页并滚动定位至评论区,于是想到了用uniapp元素节点操作uni.createSelectorQuery(),获取到节点信息然后滚动至评论区域。
刚开始把这个方法写在onLoad里面,获取到的值始终是null。
onLoad是页面初始化执行,onReady是页面初次渲染完毕执行,于是把代码放在onReady()和mounted()试试,拿到的值还是为null,onReady可能是初始化渲染一些非异步的,这里可能是异步取值时还没渲染完,于是,加点延迟就可以了。
onReady() {
setTimeout(res => {
uni.createSelectorQuery().in(this).select(".uni-comment").boundingClientRect(res => {
console.log('res', res)
uni.pageScrollTo({
duration: 0,
scrollTop: res.top
})
}).exec()
}, 600)
}
再在updated组件生命周期里试试,也是可以的,只是第一次获取的值是null会报错而已。
updated() {
uni.createSelectorQuery().in(this).select(".uni-comment").boundingClientRect(res => {
console.log('res', res)
uni.pageScrollTo({
duration: 0,
scrollTop: res.top
})
}).exec()
}
效果:拿到了该节点的集合信息。