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无具体意义,仅为初始值,不可省略

相关推荐
MXN_小南学前端4 小时前
watch详解:与computed 对比以及 Vue2 / Vue3 区别
前端·javascript·vue.js
2601_949814695 小时前
Docker部署Spring Boot + Vue项目
vue.js·spring boot·docker
Mr Xu_5 小时前
从后端数据到前端图表:深入解析 reduce 与 flatMap 的数据整形实战
前端·javascript
喜欢吃鱿鱼6 小时前
DES加解密(附带解决转义问题)-VUE
开发语言·前端·javascript
Lkstar7 小时前
逐步搞懂 Vue 的 patchChildren,把 Diff 算法拆给你看
vue.js
Jenlybein7 小时前
速学 VS Code 插件开发入门,客制化你的开发体验
前端·javascript·visual studio code
ZC跨境爬虫8 小时前
UI前端美化技能提升日志day7:(原生苹方字体全局适配+合规页脚完整像素级落地)
前端·javascript·ui·html·交互
好运的阿财8 小时前
OpenClaw工具拆解之tts+web_search
前端·javascript·python·ai·ai编程·openclaw·openclaw工具
whinc8 小时前
Node.js技术周刊 2026年第17周
前端·javascript
nbsaas-boot8 小时前
100万门店级分货系统架构设计
前端·javascript·vue.js