Uniapp 和Vue3 小程序 獲取頁面dom 方法

慈雲數據 7個月前 (05-09) 技術支持 65 0

最近在寫公司的小程序項目 技術框架 主要是Uniapp 和 Vue3

Uniapp 和Vue3 小程序 獲取頁面dom 方法
(圖片來源網絡,侵删)

恰好有個需求是要 獲取小程序頁面dom 結構 用常見的vue3獲取dom 結構不起效

記錄一下

Uniapp 和Vue3 小程序 獲取頁面dom 方法
(圖片來源網絡,侵删)

先給出正确答案

Python
  
    
      Html
      Css
      Javascrip
    
  


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();

同時記錄下錯誤答案

Python
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

Python
  
    
      Html
      Css
      Javascrip
    
  
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來獲取。

Python
// 自定義組件
export default {
  setup() {
    const myComponentRef = ref(null);
    return {
      myComponentRef
    };
  }
};
// 使用自定義組件的父組件

  


import MyCustomComponent from './MyCustomComponent.vue';
export default {
  components: {
    MyCustomComponent
  },
  setup() {
    const myComponentRef = ref(null);
    onMounted(() => {
      if (myComponentRef.value) {
        // 這裏可以訪問到自定義組件的實例
        console.log(myComponentRef.value);
      }
    });
    return {
      myComponentRef
    };
  }
};

微信掃一掃加客服

微信掃一掃加客服

點擊啓動AI問答
Draggable Icon