效果图
新建指令
vue.directive('height', { inserted(el, _binding, vnode) { const paginationref = vnode.context.$refs.paginationref const calculateheight = () => { const windowheight = window.innerheight const topoffset = el.getboundingclientrect().top const otherelementsheight = 40 let paginationheight = 0 if (paginationref && paginationref.totalpage) { paginationheight = 55 } el.style.height = `${ windowheight - topoffset - otherelementsheight - paginationheight }px` } const debouncedcalculateheight = _.debounce(calculateheight, 500) debouncedcalculateheight() window.addeventlistener('resize', debouncedcalculateheight) el.__vueheightdirective__ = debouncedcalculateheight }, unbind(el) { window.removeeventlistener('resize', el.__vueheightdirective__) delete el.__vueheightdirective__ } })
页面使用
1:el-table外层嵌套div,加指令v-height
2:el-table设置height=100%
<div v-height> <el-table height="100%"> </el-table-column> </el-table> </div>
注意,重点!
1:指令这一行 const paginationref = vnode.context.$refs.paginationref
用来判断是否显示分页器,所以如果有分页器需要在分页器增加ref,如下:
<el-pagination ref="paginationref"> </el-pagination>
2:至于这一行 paginationref.totalpage,是分页器的显示与否,比如:
<el-pagination v-if="total > 0" ref="paginationref"> </el-pagination>
至于我这里为什么叫totalpage,因为这个是经过二次封装的,没封装的就直接叫total。
同理 指令paginationref.totalpage需要修改为paginationref.total
3:有人问了paginationref.total这个total是怎么来的,怎么命名的;
这个是官网的文档的组件,paginationref这里就会获取你分页器的props。
比如:
这个total就指的elementui的分页组件的props。一般因为是用来判断total数量是不是大于0显示;
大于0就显示了分页器,所以。。。懂了吧
4:又有人问了,为什么指令不直接写在el-table里。这个你可以自己去试试,会发现滚动不了。
至于原因:因为这个指令设置的是单独style的height高度,你审查元素就会发现el-table传参的height 他需要同步设置为他下级元素样式el-table__body-wrapper的高度,所以并不是设置style为height的高度这么简单。
5:代码的_.debounce是什么。这里是用的lodash的防抖函数,自己写一个防抖函数即可。
6:有的同学就要问了,那我直接封装一个方法或者其他方法或者mixins来计算行不行
都可以,你想怎么用怎么用,mixins的话比如:
export default { data() { return { tableheight: 0 } }, mounted() { this.calculateandsetheight() }, methods: { calculateandsetheight() { if (this.$refs.tableref) { const el = this.$refs.tableref.$el const calculateheight = () => { const windowheight = window.innerheight const topoffset = el.getboundingclientrect().top const otherelementsheight = 40 let paginationheight = 0 const paginationref = this.$refs.paginationref if (paginationref && paginationref.totalpage) { paginationheight = 55 } this.tableheight = `${ windowheight - topoffset - otherelementsheight - paginationheight }px` } const throttledcalculateheight = _.debounce(calculateheight, 500) throttledcalculateheight() window.addeventlistener('resize', throttledcalculateheight) // 在组件销毁时移除事件监听器 this.$once('hook:destroyed', () => { window.removeeventlistener('resize', throttledcalculateheight) }) } } } }
页面使用:
<el-table ref="tableref" :height="tableheight">
这样就不用一个个标签像v-height div包起来了,但是ref和height就必要。
效果都是一样的,自己看着来。
ps:至于为什么要写这个功能,你能点进来看说明就是公司有一些犟货 觉得滚下去太麻烦了。或者是体验不是很好的,数据太多屏幕太小总要滚下去。
另外其实后台系统大部分用模板即可,有些模板自带有这种功能。
到此这篇关于vue2+element-ui实现el-table表格自适应高度的文章就介绍到这了,更多相关vue2 element-ui表格自适应高度内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论