Uniapp 和Vue3 小程序 获取页面dom 方法

最近在写公司的小程序项目 技术框架 主要是Uniapp 和 Vue3

恰好有个需求是要 获取小程序页面dom 结构 用常见的vue3获取dom 结构不起效

记录一下

先给出正确答案

javascript 复制代码
<template>
  <view>
    <view>
      <view>Html</view>
      <view id="target">Css</view>
      <view>Javascrip</view>
    </view>
  </view>
</template>


<script setup>
import { getCurrentInstance } from 'vue';

const instance = getCurrentInstance();

const query = uni.createSelectorQuery().in(instance);

query.select('#target').boundingClientRect(data => {
  if (data) {
    console.log("获取到布局信息", data);
    // 这里返回的data就是我们需要的dom结构
  }
}).exec();
</script>

同时记录下错误答案

javascript 复制代码
const query = uni.createSelectorQuery().in(this);
query.select('#target').boundingClientRect(data => {
  console.log(data)
}).exec();

缺少 getCurrentInstance 导入 会报错 vendor.js? sm:2306 TypeError: Cannot read property 'route' of undefined

javascript 复制代码
  <view>
    <view>
      <view>Html</view>
      <view id="target" ref="cssRef">Css</view>
      <view>Javascrip</view>
    </view>
  </view>

import { ref,onMounted,nextTick } from "vue";

const cssRef = ref(null);

onMounted(() =>{
  console.log(cssRef.value)
})

nextTick(() =>{
  console.log(cssRef.value)
})

常用的vue3 获取dom 元素方法 只会打印null 不会获取到dom结构

由于小程序环境的限制,不能直接在setup函数内部使用ref来获取DOM元素,因为小程序的视图层是由小程序框架管理的,而不是浏览器的DOM。

还有一种获取dom结构的方法 自定义组件上绑定ref

使用ref获取自定义组件实例: 如果你需要获取的是自定义组件的实例,你可以在自定义组件上使用ref属性,然后在父组件的setup函数中通过ref来获取。

javascript 复制代码
// 自定义组件
export default {
  setup() {
    const myComponentRef = ref(null);

    return {
      myComponentRef
    };
  }
};

// 使用自定义组件的父组件
<template>
  <my-custom-component ref="myComponentRef" />
</template>

<script>
import MyCustomComponent from './MyCustomComponent.vue';

export default {
  components: {
    MyCustomComponent
  },
  setup() {
    const myComponentRef = ref(null);

    onMounted(() => {
      if (myComponentRef.value) {
        // 这里可以访问到自定义组件的实例
        console.log(myComponentRef.value);
      }
    });

    return {
      myComponentRef
    };
  }
};
</script>
相关推荐
多客:duokelijie15 小时前
代练订单系统选型思路:跨品类游戏接入、订单分层管理、自动结算逻辑拆解!
数据库·mysql·微信小程序·前端框架·uni-app·php·持续部署
ruanno_top19 小时前
倒计时该用 deadline 还是每秒减一?我把两种写法都跑了一遍
vue.js
码间留白1 天前
鸿蒙端对接 BLE 血压计:从一次握手到读数入库(二)设备篇
物联网·uni-app·鸿蒙·蓝牙ble·血压计
徐小夕1 天前
下载量超 30 万的开源智能体 Prime Agent:它把自己从 TypeScript 重写成了 Rust
前端·vue.js·github
toooooop81 天前
CRMEB 故障排查笔记:安全网关只放行 GET/POST 怎么办
前端·javascript·vue.js·thinkphp6·crmeb
软件技术NINI1 天前
基于SpringBoot和Vue的项目评审系统
javascript·vue.js·spring boot·后端·spring·毕业设计·毕设
FRing031 天前
vue2干货总结3(computed计算属性、watch监听器)
开发语言·前端·vue.js·vue2
Java小卷2 天前
JuanForm vs FormCreate!Vue3 表单引擎联动配置 PK!
vue.js·低代码
AI源码2 天前
在线考试小程序
小程序·notepad++
小郎君6582 天前
Vue 多标签页的加载态设计:为什么我没有用 Suspense 实现 PageLoading
vue.js·算法