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

相关推荐
琹箐30 分钟前
Ant ASpin自定义 indicator 报错
前端·javascript·typescript
小小小小小惠34 分钟前
Responsetype blob会把接口接收的二进制文件转换成blob格式
前端·javascript
爱电摇的小码农34 分钟前
【深度探究系列(5)】:前端开发打怪升级指南:从踩坑到封神的解决方案手册
前端·javascript·css·vue.js·node.js·html5·xss
爱编程的喵1 小时前
React入门实战:从静态渲染到动态状态管理
前端·javascript
Tttian6221 小时前
npm init vue@latestnpm error code ETIMEDOUT
前端·vue.js·npm
唐叔在学习1 小时前
不用装插件!3轮对话,我用油猴脚本+AI复刻了掘金闪念笔记,真香!
javascript·浏览器
AliciaIr1 小时前
深入React事件机制:解密“合成事件”与“事件委托”的底层奥秘
javascript·react.js
元气小嘉2 小时前
前端技术小结
开发语言·前端·javascript·vue.js·人工智能
励志的大鹰哥2 小时前
V少JS基础班之第七弹
开发语言·javascript·ecmascript
cccyi72 小时前
Vue3基础知识
javascript·vue.js