当前位置:   article > 正文

Uniapp 和Vue3 小程序 获取页面dom 方法_uniapp获取dom元素 vue3写法

uniapp获取dom元素 vue3写法

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

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

记录一下

先给出正确答案

<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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

同时记录下错误答案

const query = uni.createSelectorQuery().in(this);
query.select('#target').boundingClientRect(data => {
  console.log(data)
}).exec();
  • 1
  • 2
  • 3
  • 4

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

  <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)
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

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

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

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

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

// 自定义组件
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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号