vue监听div的变化,动态渲染表格的高度

文章讲述了在Vue.js应用中,如何通过`mounted`和`beforeDestroy`生命周期钩子管理表格组件的高度,使用`watchHeights`方法实时监听窗口大小变化,确保表格高度适配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

mounted() {
  // 初始化渲染表格高度
  this.initTableHeights
},
beforeDestroy() {
  window.removeEventListener('resize', this.watchHeights)
},
methods: {
  watchHeights() {
    const el = document.getElementById('main_select')
    this.maxHeight = window.innerHeight - el.offsetHeight - 210
  },
  initTableHeights() {
    // 获取表单初始高度
    const el = document.getElementById('main_select')
    this.maxHeight = window.innerHeight - el.offsetHeight - 210
    // 监听表单高度
    window.addEventListener('resize', this.watchHeights)
  }
}

### Vue监听 `div` 元素高度变化Vue 应用程序中,可以通过多种方式监听 `div` 元素的高度变化。以下是几种常见且有效的方法: #### 方法一:使用 `ResizeObserver` 对于现代浏览器支持的情况,在模板中定义带有 `ref` 属性的元素,并通过 JavaScript 的 `ResizeObserver` API 来监控该元素尺寸的变化。 ```html <template> <div ref="elementRef"> <!-- 内容 --> </div> </template> <script> export default { mounted() { const resizeObserver = new ResizeObserver((entries) => { entries.forEach(entry => console.log('Element size:', entry.contentRect)); }); resizeObserver.observe(this.$refs.elementRef); }, unmounted() { // 清除观察者以防止内存泄漏 this.resizeObserver.unobserve(this.$refs.elementRef); } } </script> ``` 这种方法适用于 Vue 2 和 Vue 3 版本的应用程序[^1]。 #### 方法二:利用样式绑定与计算属性 另一种简单的方式是直接操作样式的内联设置,配合数据模型中的变量来进行响应式调整。 ```html <div :style="{ height: dynamicHeight + 'px' }"></div> ``` 这里的 `dynamicHeight` 可以是一个由其他逻辑控制的数据字段或计算属性[^2]。 #### 方法三:创建自定义指令处理复杂场景 如果项目需求较为特殊,比如列表页面中有动态改变大小的需求,则可以考虑编写一个自定义指令来解决这个问题。这种方式允许更灵活地应对不同情况下的布局变动。 ```javascript // 定义全局指令 v-resize-watch app.directive('resize-watch', { bind(el, binding) { let observer; function handleMutation(mutationsList) { mutationsList.forEach(mutation => { if (mutation.type === "attributes") { el.style.height = `${el.scrollHeight}px`; typeof binding.value === 'function' && binding.value(); } }) } observer = new MutationObserver(handleMutation); observer.observe(el, { attributes: true }); el.__observer__ = observer; }, unbind(el) { el.__observer__.disconnect(); } }); ``` 此方法特别适合于那些需要精确掌握子节点结构及其尺寸变更的情形[^3]。 #### 方法四:结合生命周期钩子函数确保 DOM 更新同步 考虑到某些情况下可能存在异步渲染的问题,应该借助 Vue 提供的 `nextTick()` 函数等待视图更新完毕之后再去读取最新的尺寸信息。 ```javascript import { onMounted, ref, nextTick } from 'vue'; setup() { const elementRef = ref(null); const contentHeights = []; onMounted(() => { setTimeout(() => { nextTick().then(() => { Array.from(elementRef.value.children).forEach(childEl => { contentHeights.push(childEl.offsetHeight); }); }); }, 0); // 或者根据实际情况设定延迟时间 }) return { elementRef }; } ``` 上述代码片段展示了如何安全可靠地收集一组 `.content` 类型元素的实际高度值[^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值