ElementUI中el-table表格操作列宽度自适应以及封装成全局变量

先上效果再说话

对于el-table的操作列,如果不设置width或min-width, 当表格列过少时,操作列会被分配的很宽,边缘有很大的空隙 当表格列过多时,操作列会被分配的很窄,操作列显示不下的时候会自动换行,不美观, 叔可忍婶不可忍了!

网上看了几篇文章,拿过来用不生效!!!! 自己操刀重写吧!

思路: 1.设置min-width为动态值 2.设置列class不换行 3.弄一个方法动态修改这个值 4.在更新阶段调用这个方法 5.如果有需要封装成全局方法

TIPS1:建议各位没有思路的老铁,看完思路之后尽量自己动手去写,复制粘贴提升不了技术 … TIPS1:此方法仅适用于操作列宽度自适应,如需要列宽自适应,请看我另一篇文章ElementUI中el-table表格列宽自适应以及封装

如果你的项目中有很多这样的表格都需要动态的设置操作列,可以把这个函数封装成util,然后main中声明为全局方法,以后直接调用即可

封装如下:1、新建util工具类el_table.js

/**

* 获取操作列最大宽度

* @returns

*/

export function getOperatorWidth() {

// 默认宽度

let width = 100

// 内间距

let paddingSpacing = 8

// 按钮数量

let buttonCount = 0

const operatorColumn = document.getElementsByClassName('optionDiv')

// 如果节点数量大于0-循环这个节点,

if (operatorColumn.length > 0) {

operatorColumn.forEach(item => {

// 最宽的宽度

width = width > item.offsetWidth ? width : item.offsetWidth

const buttons = item.getElementsByClassName('el-button')

// 计算 标签的数量

buttonCount = buttons.length

buttonCount = buttonCount > buttons.length ? buttonCount : buttons.length

})

if (buttonCount > 2) {

width += (paddingSpacing * (buttonCount - 1))

}

}

return width

}

// ...其他方法

2、在main.js中将el_table.js的getOperatorWidth()注册为全局方法

import Vue from 'vue'

// 1、引用js

import { getOperatorWidth} from './utils/el_table'

// 2、把工具类中的方法放入全局方法

Vue.prototype.$getOperatorWidth = getOperatorWidth;

// Vue.prototype. .......

new Vue({

el: '#app',

router,

store,

render: h => h(App)

})

3、在其他组件中的更新阶段updated中使用

data(){

//...

}

updated(){

// this.$getOperatorWidth()就是在main.js中注册的全局变量

this.dynamicWidth = this.$getOperatorWidth()

},

methods:{

// ...

}

推荐文章

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: