VueUse useElementSize 完全指南

VueUse useElementSize 完全指南

element-size-banner

📖 目录


✨ 核心特性

  • 实时追踪:自动监听元素尺寸变化
  • 响应式数据:返回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>

⚠️ 注意事项

  1. 元素引用初始化

    // ❌ 错误:未初始化ref
    const el = ref()
    // ✅ 正确:初始化为null
    const el = ref(null)
    
  2. 元素可见性

    // 元素display:none时无法获取正确尺寸
    const { width } = useElementSize(hiddenElement) // width.value = 0
    
  3. 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.x7.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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值