Vue 3函数式组件中如何获取HTML元素高度?
在Vue中获取HTML元素高度的方法
普通组件场景
直接用ref绑定目标元素,在组件挂载完成的钩子(比如mounted)里获取高度即可,Vue的ref和React的用法逻辑类似,只是语法不同:
<template> <div ref="targetElement">需要获取高度的元素</div> </template> <script> export default { mounted() { // 根据需求选择合适的高度属性 const offsetHeight = this.$refs.targetElement.offsetHeight; // 含边框、内边距 const clientHeight = this.$refs.targetElement.clientHeight; // 内边距+内容高度(不含滚动条) const scrollHeight = this.$refs.targetElement.scrollHeight; // 内容总高度(含溢出未显示部分) console.log('元素高度:', offsetHeight); } } </script>
函数式组件场景(无this)
函数式组件没有实例,没法用this.$refs,但可以通过上下文对象(Vue2)或组合式API的ref(Vue3)来实现:
Vue 2 写法
在函数式组件的渲染函数里,通过context对象访问refs,同时要把挂载钩子绑定到元素上:
<template functional> <div ref="targetElement">函数式组件内的元素</div> </template> <script> export default { functional: true, render(h, context) { // 初始化on事件对象 context.data.on = context.data.on || {}; // 在mounted钩子中获取高度 context.data.on.mounted = () => { const height = context.refs.targetElement.offsetHeight; console.log('函数式组件元素高度:', height); }; return h('div', context.data, context.children); } } </script>
Vue 3 写法
Vue3的函数式组件可以直接用组合式API,声明functional选项后,正常使用ref和onMounted即可:
<template> <div ref="targetElement">Vue3函数式组件元素</div> </template> <script setup> import { ref, onMounted } from 'vue'; const targetElement = ref(null); onMounted(() => { if (targetElement.value) { const height = targetElement.value.offsetHeight; console.log('元素高度:', height); } }); // 声明为函数式组件 defineOptions({ functional: true }); </script>
注意:不管哪种场景,都要确保元素已经挂载到DOM上再获取高度,如果是异步加载的内容(比如接口返回的列表),需要等内容渲染完成后再执行获取逻辑。
内容的提问来源于stack exchange,提问作者User123123
相关产品推荐
相关产品推荐

