1 背景
由于微信小程序中没有DOM、BOM等概念,也没有window和document对象,因此节点的获取只能采用wx.createSelectorQuery().select()的方法进行获取。但是这个方法存在很多问题,比如无法获取子组件的节点,在uniapp中的逻辑也与正常的web开发不同。我在开发中耗费了很多时间在踩坑,因此本文对这个坑点进行记录,防止后面的朋友踩坑。
2 坑点
我是在uniapp框架中开发这个项目的,以下也是结合这个框架来讲的
2.1 vue3中使用
目前查到的很多写法(包括微信的官方文档)会告诉你这样的一个写法
`wx.createSelectorQuery().in(this).select('.xxxx')`
但是vue3并不能直接获取组件实例this,因此需要getCurrentInstance()这个函数来获取组件的实例。代码如下所示,剩余部分按照官方文档即可
import {onLoad} from '@dcloudio/uni-app'
import { getCurrentInstance } from 'vue';
const instance = getCurrentInstance(); // 获取组件实例
onLoad(()=>{
wx.createSelectorQuery().in(instance).select('.xxx')
})
2.2 无法访问子组件
比如说我有一个父组件index,有一个子组件button,那么在父组件中直接使用wx.createSelectorQuery().select()是无法访问子组件中的元素的。需要获取子组件的实例instance.refs.bottom1使用in()来访问,代码如下
<template>
<bottom class="bottom" ref="bottom1"></bottom>
</template>
import { getCurrentInstance } from 'vue'
const instance = getCurrentInstance(); // 获取组件实例
onLoad(()=>{
wx.createSelectorQuery().in(instance.refs.bottom1).select('.line')
})
2.3 子组件中使用,无法访问同一组件内的元素
如果没有使用in()指定要访问的对象,默认访问的是最外层的父组件,因此只要使用2.1里面的写法就行了。
3 总结
以上是我目前遇到的一些坑,如果后续还有另外的发现会继续更新。