Skip to content

微信小程序环境无法获取 DOM 节点

难绷程度

😡红温了✅
😶无语了
😅流汗了

环境

node: v22.19.0
wot-design-uni: 1.11.1
vue: 3.5.1

Demo 复现

使用了 wot-design-uni 的 api getRect(),在页面中使用了 onLoad 钩子,控制台能打印 instance 但无法获取 DOM 节点。在 H5 环境中正常。

vue
<template>
	<view class="index">
        
    </view>
</template>

<script setup lang="ts">
onLoad(async () => {
    const instance = getCurrentInstance()
    console.log(instance) // 控制台正常打印

    await getRect(
        '.index',
        true,
        instance
    ).then((rects) => {
        console.log(rects) // 控制台不会打印,报错 No Nodes Found
    })
})
</script>

将生命周期钩子改为同步或者把 const instance = getCurrentInstance() 放到异步任务外即可

vue
<template>
	<view class="index">

    </view>
</template>

<script setup lang="ts">
const instance = getCurrentInstance()

onLoad(async () => {
    await getRect(
        '.index',
        true,
        instance
    ).then((rects) => {
        console.log(rects) // 控制台打印获取到的节点信息
    })
})
</script>