赞
踩
vue3项目,页面上的表格高度需要根据页面高度变化进行动态计算赋值,实现如下。
如下图表格,其父元素(红框元素)高度不是具体值,表格需要设置一个最大高度以便超出后显示滚动条,同时确保页面高度变化时(浏览器窗口大小改变)表格高度动态计算。
代码实现:
<template> <div class="table-wrap"> <el-table ref="tableRef" :data="tableData" :max-height="tableHeight" style="width: 80%"> <el-table-column prop="id" label="ID" width="180" /> <el-table-column prop="date" label="Date" width="180" /> <el-table-column prop="name" label="Name" width="180" /> <el-table-column prop="address" width="180" label="Address" /> <el-table-column prop="address" width="180" label="Address" /> <el-table-column prop="address" label="Address" /> </el-table> </div> </template> <script setup> import {reactive,ref,onMounted,onUnmounted,nextTick} from 'vue' let tableData = reactive([]) let tableRef = ref(null) const tableHeight = ref() // 生成表格数据 let tableDataList = [] for(let i=0;i<50;i++){ tableDataList.push({ id: i + 1, date: '2024年3月19日', name: 'sy', address: 'address' }) } tableData = tableDataList const computedHeight = () => { if (tableHeight.value) { tableHeight.value = window.innerHeight - tableRef.value.$el.offsetTop - 180 } } onMounted(() => { nextTick(() => { tableHeight.value = window.innerHeight - tableRef.value.$el.offsetTop - 180 window.addEventListener('resize', computedHeight) }) }) onUnmounted(() => { window.removeEventListener('resize', computedHeight) }) </script> <style> .table-wrap{ height: calc(100vh - 160px); border: 1px solid red; overflow: hidden; } </style>
关于 window.innerHeight:
关于offsetTop:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。