el-table高度自适应
第一种方式 dom监听
export async function setTableHeight(table) {
let tableHeight = 0 //表格max-height
let safeDistance = 10 // 页面在iframe时留出部分高度
let bottomHeight = 80 //留出表格分页栏高度
await this.$nextTick(() => {
let {
top
} = document.querySelector(table).getBoundingClientRect() //获取元素四个方向的距离
tableHeight = document.getElementById('app').offsetHeight - top - bottomHeight
if (self.frameElement && self.frameElement.tagName == 'IFRAME') {
tableHeight = tableHeight - safeDistance
}
})
return tableHeight
}
使用
//传入表格的id或class 注意格式 .class / #id ,不是表格也可以用,自行调整底部距离即可
// 将tableHeight 作为表格的 max-height 即可 <el-table :max-height="tableHeight">
mounted(){
this.getTheight('.el-table').then((val) => {
this.tableHeight = val
})
}
第二种方式 好用 推荐
getHeight() {
let getHeightFromBottom = (element, variableHeight) => {
const elementRect = element.getBoundingClientRect().top;
const windowHeight = window.innerHeight;
const elementHeightFromBottom = windowHeight - elementRect;
const result = elementHeightFromBottom - variableHeight;
return result;
}
const element = document.getElementById('myTable');
const variableHeight = 70; // 给定的变量高度 一般留于分页器高度
this.autoHeight =getHeightFromBottom(element, variableHeight);
},
第三种方式 自定义指令
在el-table中 搭配height使用
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) || 30
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)
}
}
//----------------------新建index文件 引入以上文件----------------------------
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
//单页面使用
<el-table
ref="table"
// 自定义指令,bottomOffset 代表距离底部的距离
v-adaptive="{bottomOffset: 85}"
// 高度属性,100无具体意义,仅为初始值,不可省略
height="100px"
>
... ...
</table>
import adaptive from '@/directive/el-table'
export default {
name:'Test',
directives: { adaptive },
... ...
}
//全局使用
import adaptive from './directive/el-table'
Vue.use(adaptive)
以上三种方式推荐第二种,比较方便使用;