微信小程序中组件获取视图对象

在小程序中,我想获取其中一个组件的宽高,用来计算位置。然后查阅小程序文档,找到了

 wx.createSelectorQuery().select('#the-id').boundingClientRect(function(rect){
      rect.id      // 节点的ID
      rect.dataset // 节点的dataset
      rect.left    // 节点的左边界坐标
      rect.right   // 节点的右边界坐标
      rect.top     // 节点的上边界坐标
      rect.bottom  // 节点的下边界坐标
      rect.width   // 节点的宽度
      rect.height  // 节点的高度
    }).exec()

这里的select 是类似于选择器。
然后我是在组件的生命周期中获取,使用的ready

 lifetimes: {
    ready: function() {
      // 在组件在视图层布局完成后执行
      //创建节点选择器
      var touchModel = this;
      wx.createSelectorQuery().select('#weiyideID').boundingClientRect(function (rect) {
        touchModel.data.width = rect.width
        touchModel.data.height = rect.height
      }).exec()

    }
  }

然后问题就来了,我获取的rect一直是null。也不知道什么原因
网查资料都没有找到什么参考。开始是怀疑生命周期的事,可能是没有生成页面所以获取不到。但是加了延时执行或者是在使用时获取都是null。
再一次查阅微信小程序文档,把那几个selectQuery都看了一遍
在这里插入图片描述

然后就看到了 obj.in() 这个方法,之前查资料也查到过,这是人家博客中写的

obj.in(component):没用过这个方法,多用于组件的选择器。

我自己定义的就是组件,那么是不是也要使用这个
修改之后

 lifetimes: {
    ready: function() {
      // 在组件在视图层布局完成后执行
      //创建节点选择器
      var touchModel = this;
      wx.createSelectorQuery().in(this).select('#weiyideID').boundingClientRect(function (rect) {
        touchModel.data.width = rect.width
        touchModel.data.height = rect.height
      }).exec()

    }
  }

执行果然获取到了对象
参考:https://developers.weixin.qq.com/miniprogram/dev/api/wxml/SelectorQuery.in.html

发布了95 篇原创文章 · 获赞 36 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/u013513053/article/details/92793162
今日推荐