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

相关推荐
by__csdn1 分钟前
ES6新特性全攻略:JavaScript的现代革命
开发语言·前端·javascript·typescript·ecmascript·es6·js
用户841794814563 分钟前
如何使用 vxe-gantt table 甘特图来实现多个维度视图展示,支持切换年视图、月视图、周视图等
vue.js
by__csdn4 分钟前
Vue 双向数据绑定深度解析:从原理到实践的全方位指南
前端·javascript·vue.js·typescript·前端框架·vue·ecmascript
奋斗吧程序媛9 分钟前
前端 Token 管理与最佳实践
前端·vue.js
汉堡大王952724 分钟前
JavaScript类型侦探:四大神器让你一眼看穿变量真身
前端·javascript
Debroon26 分钟前
从零开始手写ReAct Agent
前端·javascript·react.js
软件技术NINI27 分钟前
html css js网页制作成品——成毅html+css+js 5页附源码
javascript·css·html
CryptoRzz35 分钟前
对接墨西哥股票市场 k线图表数据klinechart 数据源API
开发语言·javascript·web3·ecmascript
chilavert31840 分钟前
技术演进中的开发沉思-230 Ajax:Prototype.js 重构原生 DOM
开发语言·前端·javascript
zhousenshan43 分钟前
vue3 createApp用法
vue.js