uniapp如何获取dom元素
在uniapp中如何获取DOM元素?我尝试使用document.querySelector但无法生效,请问在uniapp中正确的DOM操作方法是什么?是否支持ref获取节点?跨平台时有哪些注意事项?
2 回复
在uni-app中,使用this.$refs.xxx获取组件实例,再通过.$el获取DOM节点。注意:H5端可正常获取,但小程序端不支持直接操作DOM。
在 UniApp 中,由于跨平台特性,不能直接使用传统 Web 的 DOM API(如 document.getElementById)。推荐使用 Vue.js 的 ref 来获取组件实例,或使用 UniApp 提供的节点查询 API uni.createSelectorQuery()。
方法一:使用 Vue ref(适用于组件)
在模板中为元素添加 ref 属性,然后通过 this.$refs 访问:
<template>
<view ref="myElement">这是一个元素</view>
</template>
<script>
export default {
mounted() {
// 获取组件实例
const element = this.$refs.myElement;
console.log(element); // 可访问组件属性和方法
}
}
</script>
方法二:使用 uni.createSelectorQuery()(通用方法)
通过选择器查询节点信息,支持跨平台:
<template>
<view id="myElement">这是一个元素</view>
</template>
<script>
export default {
mounted() {
// 创建节点查询
const query = uni.createSelectorQuery().in(this);
query.select('#myElement').boundingClientRect(data => {
console.log(data); // 获取位置、尺寸等信息
}).exec();
}
}
</script>
注意事项:
-
平台差异:
- H5 端可能支持部分 DOM API,但为保持跨平台兼容,建议使用上述方法。
- 小程序端需在
mounted后调用createSelectorQuery。
-
常用场景:
- 获取位置/尺寸:使用
boundingClientRect。 - 获取滚动信息:结合
selectViewport。 - 操作组件:优先使用
ref。
- 获取位置/尺寸:使用
示例:获取元素宽度和高度
const query = uni.createSelectorQuery().in(this);
query.select('#myElement').boundingClientRect(rect => {
if (rect) {
console.log('宽度:', rect.width, '高度:', rect.height);
}
}).exec();
以上方法覆盖了 UniApp 中获取元素的常见需求,优先推荐 createSelectorQuery 处理跨平台兼容性。

