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

打印 上一主题 下一主题

主题 550|帖子 550|积分 1650

近来在写公司的小程序项目 技能框架 主要是Uniapp 和 Vue3
恰好有个需求是要 获取小程序页面dom 结构 用常见的vue3获取dom 结构不起效
记录一下
先给出准确答案
  1. <template>
  2.   <view>
  3.     <view>
  4.       <view>Html</view>
  5.       <view id="target">Css</view>
  6.       <view>Javascrip</view>
  7.     </view>
  8.   </view>
  9. </template>
  10. <script setup>
  11. import { getCurrentInstance } from 'vue';
  12. const instance = getCurrentInstance();
  13. const query = uni.createSelectorQuery().in(instance);
  14. query.select('#target').boundingClientRect(data => {
  15.   if (data) {
  16.     console.log("获取到布局信息", data);
  17.     // 这里返回的data就是我们需要的dom结构
  18.   }
  19. }).exec();
  20. </script>
复制代码
同时记录下错误答案
  1. const query = uni.createSelectorQuery().in(this);
  2. query.select('#target').boundingClientRect(data => {
  3.   console.log(data)
  4. }).exec();
复制代码
缺少 getCurrentInstance 导入 会报错 vendor.js? [sm]:2306 TypeError: Cannot read property ‘route’ of undefined
  1.   <view>
  2.     <view>
  3.       <view>Html</view>
  4.       <view id="target" ref="cssRef">Css</view>
  5.       <view>Javascrip</view>
  6.     </view>
  7.   </view>
  8. import { ref,onMounted,nextTick } from "vue";
  9. const cssRef = ref(null);
  10. onMounted(() =>{
  11.   console.log(cssRef.value)
  12. })
  13. nextTick(() =>{
  14.   console.log(cssRef.value)
  15. })
复制代码
常用的vue3 获取dom 元素方法 只会打印null 不会获取到dom结构
由于小程序环境的限定,不能直接在setup函数内部使用ref来获取DOM元素,由于小程序的视图层是由小程序框架管理的,而不是欣赏器的DOM。
还有一种获取dom结构的方法 自界说组件上绑定ref
使用ref获取自界说组件实例: 假如你须要获取的是自界说组件的实例,你可以在自界说组件上使用ref属性,然后在父组件的setup函数中通过ref来获取。
  1. // 自定义组件
  2. export default {
  3.   setup() {
  4.     const myComponentRef = ref(null);
  5.     return {
  6.       myComponentRef
  7.     };
  8.   }
  9. };
  10. // 使用自定义组件的父组件
  11. <template>
  12.   <my-custom-component ref="myComponentRef" />
  13. </template>
  14. <script>
  15. import MyCustomComponent from './MyCustomComponent.vue';
  16. export default {
  17.   components: {
  18.     MyCustomComponent
  19.   },
  20.   setup() {
  21.     const myComponentRef = ref(null);
  22.     onMounted(() => {
  23.       if (myComponentRef.value) {
  24.         // 这里可以访问到自定义组件的实例
  25.         console.log(myComponentRef.value);
  26.       }
  27.     });
  28.     return {
  29.       myComponentRef
  30.     };
  31.   }
  32. };
  33. </script>
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

飞不高

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表