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

相关推荐
橘子星18 分钟前
RAG 实战:3 步将整本《天龙八部》存入向量数据库(一)
javascript·人工智能
han_hanker26 分钟前
SQL语法 , BETWEEN ... AND ...,比较运算符
前端·javascript·sql
mONESY1 小时前
从零搭建 Milvus 向量知识库:Node.js 实现日记 RAG 检索全流程实战
javascript
林间码客1 小时前
全栈视角下的 Mock 指南:从后端单元测试到前端 Vue 3 联调
前端·vue.js·单元测试
张元清1 小时前
React usePrevious Hook:追踪上一次的 State 和 Props(2026)
javascript·react.js
Cobyte1 小时前
手写 Rollup 插件实现解析 Vue 文件
前端·javascript·vue.js
安冬的码畜日常2 小时前
【工欲善其事】深入理解 Node.js 带并发上限的异步任务批量执行逻辑
javascript·设计模式·node.js·ai编程·异步编程·并发执行
meilindehuzi_a3 小时前
Vue3组件样式隔离与组件通信实战:从 scoped、props 校验到记事本应用
前端·javascript·vue.js
To_OC11 小时前
我被 useState 坑了两次之后,终于把它的脾气摸透了
前端·javascript·react.js
Luu.ྀ11 小时前
React详细笔记
javascript·笔记·react.js