项目中需要获取到数据更新之后元素的高度,网上的文章说可以使用ref,我在view里面添加了ref,但获取不到:
<view v-show="current === 0" id="own_view" class="own_view" ref="own_view">
。。。
mounted() {
this.$nextTick(function(){
console.log("mounted this.$refs.own_view", this.$refs.own_view);
console.log("mounted this.$refs['own_view']", this.$refs["own_view"]);
})
},
哪怕是放在nextTick中也是一样的undefined。
后来发现了uni.createSelectorQuery的办法来获取,感觉有点儿麻烦,但已经可以工作了。
获取数据更新后的元素高度、宽度
想了一下,高度其实是在数据更新之后动态改变的,所以最好是写在获取并更新成功之后。
getPractices() {
let self = this
let toServerUrl =
`${$backHost}/api/v1/users/${globalData.$user_id}/pth_sentences/${this.id}/recent_practices`
// console.log("getPractices url:", toServerUrl);
this.$request({
url: toServerUrl,
success: ((res) => {
console.log("getPractices:", JSON.stringify(res));
self.practices = res
self.$nextTick(function(){
const query = uni.createSelectorQuery().in(self);
query.select('#own_view').boundingClientRect(data => {
console.log("getPractices 得到布局位置信息" + JSON.stringify(data));
console.log("own_view 高度" + data.height);
console.log("own_view 宽度" + data.width);
self.own_view_height = data.height
}).exec();
})
})
});
},
即从后台服务器获取到practices之后,在
self.$nextTick
中使用uni.createSelectorQuery,这里我是通过id own_view来得到整个view, 记得在select中添加#号,相当于是dom选择的办法!此选择器有一些限制:
- ID选择器:
#the-id
- class选择器(可以连续指定多个):
.a-class.another-class
- 子元素选择器:
.the-parent > .the-child
- 后代选择器:
.the-ancestor .the-descendant
- 跨自定义组件的后代选择器:
.the-ancestor >>> .the-descendant
- 多选择器的并集:
#a-node, .some-other-nodes
没写在nextTick里面也是获取不到的,数据是更新了,但渲染还没有完成,而写在nextTick里面就表示的是,数据已经更新完成并渲染。所以,最终的解决方案就是把获取元素的高度、宽度放在更新数据之后!
官方文档
https://uniapp.dcloud.io/api/ui/nodes-info?id=createselectorquery
我是@爱玩的安哥,关注我获取更多有用知识