在 UniApp 中,原生 App 环境不是运行在浏览器中,无法使用 document.getElementById
、document.querySelector
等 Web API。建议使用以下方式替代。
✅ 推荐 1:使用 ref
引用元素
<template>
<view ref="myView">内容</view>
</template>
<script setup>
import { onMounted, ref } from 'vue'
const myView = ref(null)
onMounted(() => {
// 虽然不能直接获取 DOM,但可以获取组件引用
console.log('myView:', myView.value)
})
</script>
✅ 推荐 2:使用 uni.createSelectorQuery
获取元素位置/尺寸
<template>
<view class="my-view">测试内容</view>
</template>
<script setup>
import { onMounted } from 'vue'
onMounted(() => {
const query = uni.createSelectorQuery().in(uni)
query.select('.my-view').boundingClientRect(data => {
console.log('元素位置和大小:', data)
}).exec()
})
</script>
❌ 不推荐使用(App端无效)
// 以下在 App 中不可用
document.getElementById('myView')
document.querySelector('.my-view')
document.body
window.addEventListener('resize', () => {})
✅ 替代方案总结表
不推荐 Web API | 推荐写法 |
---|---|
document.getElementById | 使用 ref 或 uni.createSelectorQuery() |
document.querySelector | 使用 uni.createSelectorQuery() |
document.body | 控制布局用组件或响应式变量 |
window.addEventListener | 使用生命周期 onShow/onHide |
🌟 推荐始终使用
ref
和uni.createSelectorQuery
来替代浏览器 API,这样能确保你的代码在 App、小程序和 H5 都能正常运行。