VueUse useElementSize 完全指南
📖 目录
✨ 核心特性
- 实时追踪:自动监听元素尺寸变化
- 响应式数据:返回Ref类型的宽高数值
- 自动清理:组件卸载时自动移除监听
- SSR友好:支持服务端渲染
- 多框架兼容:Vue2/Vue3通用
🚀 快速入门
安装
npm install @vueuse/core
# 或
yarn add @vueuse/core
### 基础用法
```vue
<template>
<div ref="targetEl">调整浏览器窗口查看变化</div>
<p>宽度: {{ width }}px</p>
<p>高度: {{ height }}px</p>
</template>
<script setup>
import { ref } from 'vue'
import { useElementSize } from '@vueuse/core'
const targetEl = ref(null)
const { width, height } = useElementSize(targetEl)
</script>
🔍 深度解析
响应式尺寸
<script setup>
// 响应式更新示例
const { width } = useElementSize(targetEl)
watch(width, (newVal) => {
console.log('宽度变化:', newVal)
})
</script>
动态元素
<script setup>
// 动态切换监听目标
const dynamicTarget = ref(null)
const { width } = useElementSize(dynamicTarget)
function switchTarget(newEl) {
dynamicTarget.value = newEl
}
</script>
🎯 实战技巧
自适应布局
<template>
<div ref="container">
<div :style="{ fontSize: fontSize + 'px' }">
自适应文字大小
</div>
</div>
</template>
<script setup>
const container = ref(null)
const { width } = useElementSize(container)
const fontSize = computed(() => {
return Math.min(24, width.value * 0.1)
})
</script>
性能优化
<script setup>
// 节流处理
const { width } = useElementSize(targetEl, {
throttle: 300 // 300ms节流
})
// 初始化默认值
const { width = ref(0) } = useElementSize(targetEl)
</script>
⚠️ 注意事项
-
元素引用初始化
// ❌ 错误:未初始化ref const el = ref() // ✅ 正确:初始化为null const el = ref(null)
-
元素可见性
// 元素display:none时无法获取正确尺寸 const { width } = useElementSize(hiddenElement) // width.value = 0
-
CSS影响
/* 确保元素有明确尺寸 */ .measured-element { width: 100%; height: 100%; contain: strict; }
❓ 常见问题
Q1: 如何监听多个元素?
const el1 = ref(null)
const el2 = ref(null)
const size1 = useElementSize(el1)
const size2 = useElementSize(el2)
Q2: 如何手动触发更新?
const { update } = useElementSize(targetEl)
// 强制刷新尺寸
update()
Q3: 支持iframe内容吗?
// 监听iframe内部元素
const iframeContent = ref(null)
const { width } = useElementSize(iframeContent, {
box: 'content-box' // 指定测量模式
})
版本兼容性
Vue 版本 | VueUse 版本 | 注意事项 |
---|---|---|
3.x | >= 4.0 | 推荐使用 |
2.x | 7.x | 需要@vue/composition-api |
## 最佳实践建议
1. **组件封装**:创建可复用的尺寸感知组件
2. **性能监控**:配合usePerformance监控重排开销
3. **动画优化**:在resize事件中使用requestAnimationFrame
4. **错误处理**:添加try-catch防止未定义元素
```vue
<!-- SizeMonitor.vue -->
<script setup>
const props = defineProps({
target: {
type: HTMLElement,
default: null
}
})
const { width, height } = useElementSize(() => props.target)
</script>