开发中表格功能是很常见的功能,自适应高度也是比较头疼的问题。
实现方法一:指令
创建目录src/directive/table
adaptive.js
import { addResizeListener, removeResizeListener } from 'element-ui/src/utils/resize-event'
// 设置表格最小高度
const tableMin = 200
// 设置表格高度
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
// 计算列表高度并设置
let height = window.innerHeight - el.getBoundingClientRect().top - bottomOffset
// 设置最小高度
height = height < tableMin ? tableMin : height
$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)
addResizeListener(el, el.resizeListener)
},
// 绑定默认高度
async inserted(el, binding, vnode) {
await doResize(el, binding, vnode)
},
// 组件发生变化时触发
async componentUpdated(el, binding, vnode) {
await doResize(el, binding, vnode)
},
// 销毁时设置
unbind(el) {
// 移除resize监听
removeResizeListener(el, el.resizeListener)
}
}
index.js
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
组件内引用
import adaptive from '@/directive/table/index.js'
...
directives: { adaptive },
...
<el-table
ref="table"
:data="tableData.data"
height="100px"
v-adaptive="{bottomOffset: 84}"
border>
...
全局引用
import adaptive from './directive/table';
Vue.use(adaptive)
参考文章:https://juejin.cn/post/6844904153534332935
实现方法二:
监听resize方法实现
import { debounce } from '@/utils/index'
<el-table
ref="table"
:data="tableData.data"
:height="tableHeight"
border
>
let that = this
// debounce 是防抖方法
window.addEventListener('resize', debounce(() => {
that.resizeEvent()
}, 100))
resizeEvent() {
// 计算高度赋值就可以
this.tableHeight = xxx
}
// 销毁页面时,移除监听方法
beforeDestroy() {
window.removeEventListener('resize', debounce())
}
网友评论