element table 自适应外面盒子的高度,可以通过添加自定义指令来解决
1 在src下面创建一个directive文件夹,再创建index.js和tableHeight.js
tableHeight.js 代码如下:
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'`)
// }
// console.log($table, '$table$table$table$table')
// 获取距底部距离(用于展示页码等信息)
const bottomOffset = (value && value.bottomOffset) || 30
if (!$table) return
// 计算列表高度并设置
const height = window.innerHeight - el.getBoundingClientRect().top - bottomOffset
// $table.layout.setMaxHeight(height)
$table.layout.setHeight(height)
// $table.maxHeight = 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.js代码如下:
import tableHeight from './tableHeight'
const install = function (Vue) {
// 绑定v-adaptive指令
Vue.directive('tableHeight', tableHeight)
}
if (window.Vue) {
window['tableHeight'] = tableHeight
// eslint-disable-next-line no-undef
Vue.use(install)
}
tableHeight.install = install
export default tableHeight
main.js 里面添加如图代码
// 这个是你刚刚写的index.js的路径
import tableHeight from '@/directive/index.js'
// 表格自适应指令
Vue.use(tableHeight)
模板里面的使用如图:
<el-table :data="tableData" stripe style="width: 100%" height="100px" v-tableHeight="{bottomOffset: 60}">
<el-table-column prop="date" label="日期" width="180"></el-table-column>
<el-table-column prop="name" label="姓名" width="180"></el-table-column>
<el-table-column prop="address" label="地址"></el-table-column>
<el-table-column prop="caozuo" label="操作" fixed="right"></el-table-column>
</el-table>
网友评论