el-table添加固定高度height后高度自适应

0 效果

1 添加自定义指令

新建目录src/directive/el-table
在el-table目录下新建文件adaptive.js

javascript 复制代码
import { addResizeListener, removeResizeListener } from 'element-ui/src/utils/resize-event'
 
 // 设置表格高度
 const doResize = async(el, binding, vnode) => {
 // 获取表格Dom对象
 const { componentInstance: $table } = await vnode
 // 获取调用传递过来的数据 
 const { value } = binding
 
 if (!$table.height) {
  throw new Error(`el-$table must set the height. Such as height='100px'`)
 }
 // 获取距底部距离(用于展示页码等信息)
 const bottomOffset = (value && value.bottomOffset) || 90
 
 if (!$table) return
 
 // 计算列表高度并设置
 const height = window.innerHeight - el.getBoundingClientRect().top - bottomOffset
 $table.layout.setHeight(height)
 $table.doLayout()
}
 
export default {  
  // 初始化设置
  bind(el, binding, vnode) { 
    // 设置resize监听方法
    el.resizeListener = async() => { 
      await doResize(el, binding, vnode)
    }    
    // 绑定监听方法到addResizeListener
    addResizeListener(window.document.body, el.resizeListener)  
  },  
  // 绑定默认高度
  async inserted(el, binding, vnode) { 
    await doResize(el, binding, vnode)  
  },  
  // 销毁时设置
  unbind(el) { 
    // 移除resize监听
    removeResizeListener(el, el.resizeListener)  
  }
}

在el-table目录下新建index.js

javascript 复制代码
import adaptive from './adaptive'
 
const install = function(Vue) {   
  // 绑定v-adaptive指令
  Vue.directive('adaptive', adaptive)
}
 
if (window.Vue) {
  window['adaptive'] = adaptive  
  // eslint-disable-next-line no-undef 
  Vue.use(install)
}
 
adaptive.install = install
 
export default adaptive

2 引入

2.1 单个vue文件引入

在所需使用的vue页面中引入
import adaptive from '.../.../.../src/directive/el-table'

2.2 全局引入

在main.js中引入

3 使用

在el-table标签中添加属性

v-adaptive:自定义指令,bottomOffset 代表距离底部的距离

height:高度属性,100无具体意义,仅为初始值,不可省略

相关推荐
执子念的飞鱼2 分钟前
Vue 3 文件预览落地:鉴权 Blob、Worker/WASM 与内网子路径部署
vue.js·webassembly
无人生还19 分钟前
从 Vue3 到 React · 快速上手系列第 11 篇:状态管理
前端·vue.js·react.js
Hilaku30 分钟前
当 AI 一天写完一周的代码,我们还剩什么优势?
前端·javascript·程序员
无责任此方_修行中33 分钟前
换个版本号就能升级?可没那简单:pnpm 11 升级踩坑记
javascript·后端·npm
尘世中一位迷途小书童35 分钟前
无人机航线里的云台角度怎么调?Cesium 做了个视锥 + 鹰眼联动
前端·javascript·数据可视化
张元清36 分钟前
React useMeasure Hook:用 ResizeObserver 测量 DOM 元素 (2026)
javascript·react.js
A24207349301 小时前
Vue3 + TypeScript:后端数据在表格内渲染后进行增删改的完整实现步骤
前端·javascript·typescript
他们叫我 悦儿遥遥雨1 小时前
.NET 8 Web开发入门(六):Blazor 全栈开发——告别 JavaScript 焦虑
前端·javascript·.net
其美杰布-富贵-李1 小时前
Vue 3 模块导入教程:import、export 与文件组织
前端·javascript·vue.js
weipt1 小时前
springboot项目运行的几种方式
javascript·css·html