解决element表格自适应高度问题
在写公司后台项目的时候遇到一个需求,要求表格页面不能有滚动条,所以必须封装一个公共方法来实现表格自适应高度
第一步 实现自定义指令去监听表格元素高度变化
我这边使用封住思想 首先创建在obSize文件夹下创建index.js内容如下
//
const map = new WeakMap()
// ob监听
const ob = new ResizeObserver((entries) => {
for (const entry of entries) {
// 处理元素对应的回调
const handler = map.get(entry.target)
if (handler) {
const box = entry.borderBoxSize[0]
// 循环entry.target 累加offsetTop 从而得到距离页面顶部距离
let setTop = countTop(entry.target, 0)
handler({
width: box.inlineSize,
height: box.blockSize,
entry: entry,
bodHeight: window.document.body.clientHeight,
setTop: setTop,
tableHeight: (window.document.body.clientHeight - setTop - 50 - box.inlineSize) > 0 ? '' : window.document.body.clientHeight - setTop - 72
})
}
}
})
export function countTop(el, topn) {
if (el.offsetParent) {
return countTop(el.offsetParent, topn + el.offsetTop)
} else {
return topn
}
}
export default {
inserted(el, binding) {
ob.observe(el)
// 监听el元素尺度的变化
map.set(el, binding.value)
},
unbind(el) {
// 取消监听
ob.unobserve(el)
},
}
注册vue指令在directive文件夹index.js文件中
javascript
import obSize from './obSize'
const install = function (Vue) {
//这里可以放入多个自定义指令
Vue.directive('ob-size', obSize)
}
if (window.Vue) {
Vue.use(install); // eslint-disable-line
}
export default install
在main.js引入directive
javascript
import directive from './directive'
Vue.use(directive)
第二步 封装mixins
在mixins文件夹内创建estimateTableHeight.js内容如下 70 代表距离页面底部的高度
javascript
import { countTop } from '@/directive/obSize'
export default {
data() {
return {
tableHeight: 0,
}
},
methods: {
handleSizeChange(e) {
this.tableHeight = e.tableHeight;
},
},
// 监听showSearch
watch: {
showSearch(val) {
// 获取element table元素
const dome = document.getElementsByClassName('el-table');
let setTop = countTop(dome, 0)
this.tableHeight = window.document.body.clientHeight - setTop - 70
},
},
mounted() {
//监听页面尺寸变化
window.addEventListener('resize', () => {
const dome = document.getElementsByClassName('el-table');
let setTop = countTop(dome, 0)
this.tableHeight = window.document.body.clientHeight - setTop - 70
});
},
}
第三步 在页面引入
引入 import estimateTableHeight from "@/mixins/estimateTableHeight";
export default { mixins: [estimateTableHeight], }
在el-table上加入 v-ob-size="handleSizeChange" :height="tableHeight"
ini
<el-table
v-ob-size="handleSizeChange"
:height="tableHeight"
v-loading="loading"
:data="List"
>
大功告成!!!!!!!!!!!!!!!