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

相关推荐
前端君5 小时前
实现最大异步并发执行队列
javascript
知识分享小能手6 小时前
React学习教程,从入门到精通,React 组件核心语法知识点详解(类组件体系)(19)
前端·javascript·vue.js·学习·react.js·react·anti-design-vue
蚂蚁RichLab前端团队7 小时前
🚀🚀🚀 RichLab - 花呗前端团队招贤纳士 - 【转岗/内推/社招】
前端·javascript·人工智能
萌萌哒草头将军7 小时前
Oxc 和 Rolldown Q4 更新计划速览!🚀🚀🚀
javascript·vue.js·vite
Qlittleboy7 小时前
uniapp如何使用本身的字体图标
javascript·vue.js·uni-app
小白菜学前端8 小时前
vue2 常用内置指令总结
前端·vue.js
林_深时见鹿8 小时前
Vue + ElementPlus 自定义指令控制输入框只可以输入数字
前端·javascript·vue.js
GDAL8 小时前
Knockout.js 任务调度模块详解
javascript·knockout
椒盐螺丝钉8 小时前
Vue组件化开发介绍
前端·javascript·vue.js
koooo~8 小时前
v-model与-sync的演变和融合
前端·javascript·vue.js