uni-app nvue组件列表只有第一个组件可以获取到元素信息

uni-app nvue组件列表只有第一个组件可以获取到元素信息

产品分类

  • uniapp/App

PC开发环境

操作系统 版本号
Windows win10

手机环境

系统 版本号 厂商 机型
Android Android 11 一加 8t

页面类型

  • nvue

打包方式

  • 云端

项目创建方式

  • HBuilderX

App下载地址或H5网址

示例代码

<view  :style="txtHeight>110 && showTxt? 'height:110px':'height:'+txtHeight+'px;'+showTxt?'padding-bottom:22px':''"  class="txt more" ref="txt" id="txt">
<rich-text :nodes="text" style="font-size: 15px;line-height: 22px;color: #242424;"></rich-text>
</view>  
let that = this;
// #ifdef APP-PLUS
const dom = weex.requireModule('dom')
const result = dom.getComponentRect(this.$refs.txt, option => {
console.log('getComponentRect:', option.size.height)
})
//#endif

操作步骤

预期结果

  • 14:40:58.629 getComponentRect:, [Number] 238.57777404785156 at pages/circle/index/circle-item.nvue:181
  • 14:40:58.629 getComponentRect:, [Number] 238.57777404785156 at pages/circle/index/circle-item.nvue:181
  • 14:40:58.629 getComponentRect:, [Number] 238.57777404785156 at pages/circle/index/circle-item.nvue:181
  • 14:40:58.629 getComponentRect:, [Number] 238.57777404785156 at pages/circle/index/circle-item.nvue:181
  • 14:40:58.629 getComponentRect:, [Number] 238.57777404785156 at pages/circle/index/circle-item.nvue:181

实际结果

  • 14:40:58.629 getComponentRect:, [Number] 238.57777404785156 at pages/circle/index/circle-item.nvue:181
  • 14:40:58.650 getComponentRect:, [Number] 0 at pages/circle/index/circle-item.nvue:181
  • 14:40:58.673 getComponentRect:, [Number] 0 at pages/circle/index/circle-item.nvue:181
  • 14:40:58.692 getComponentRect:, [Number] 0 at pages/circle/index/circle-item.nvue:181
  • 14:40:58.714 getComponentRect:, [Number] 0 at pages/circle/index/circle-item.nvue:181
  • 14:40:58.734 getComponentRect:, [Number] 0 at pages/circle/index/circle-item.nvue:181

bug描述

  • 在nvue组件中使用getComponentRect获取元素信息,结果循环生成的组件只有第一个组件可以获取到信息

更多关于uni-app nvue组件列表只有第一个组件可以获取到元素信息的实战教程也可以访问 https://www.itying.com/category-93-b0.html

7 回复

如果有多个相同的ref(txt) this.$refs.txt 是个数组。要遍历 this.$refs.txt[0],this.$refs.txt[1]…

更多关于uni-app nvue组件列表只有第一个组件可以获取到元素信息的实战教程也可以访问 https://www.itying.com/category-93-b0.html


不是的,获取元素信息的方法是写在组件的mounted里面,所以只有一个refs.txt,是个对象来的

解决了吗

解决了吗,遇到同样问题

贴代码看看

我也发现了,在安卓下只有第一个能获取,其他都是0,ios是没问题的

这是一个典型的 nvue 中 getComponentRect 异步执行时序问题。在循环渲染组件时,后续组件的 DOM 可能尚未完全渲染完成就执行了获取元素信息的代码。

建议在 mounted 生命周期中使用 $nextTick 确保 DOM 渲染完成后再获取元素信息:

// #ifdef APP-PLUS
mounted() {
    this.$nextTick(() => {
        const dom = weex.requireModule('dom')
        dom.getComponentRect(this.$refs.txt, option => {
            console.log('getComponentRect:', option.size.height)
        })
    })
}
//#endif
回到顶部