在uniapp和Vue中,可以使用内置的指令或API来获取元素的宽高。
- 使用Vue的
ref属性和this.$refs来获取DOM元素。
<template>
<view>
<view ref="box" style="width: 100px; height: 100px;"></view>
</view>
</template>
<script>
export default {
mounted() {
this.$nextTick(() => {
const box = this.$refs.box;
const width = box.offsetWidth;
const height = box.offsetHeight;
console.log(`宽: ${width}, 高: ${height}`);
});
}
}
</script>- 使用uniapp提供的
uni.createSelectorQuery()API。
export default {
mounted() {
const query = uni.createSelectorQuery().in(this);
query.select('#box').boundingClientRect(data => {
const width = data.width;
const height = data.height;
console.log(`宽: ${width}, 高: ${height}`);
}).exec();
}
}在上述例子中,#box是你想要获取宽高的元素的ID。
请注意,获取元素宽高的操作应在页面渲染完成后进行,因此通常放在mounted钩子中,或者使用this.$nextTick确保DOM已经更新。对于uniapp,使用uni.createSelectorQuery()并调用其exec方法来执行查询。