Bootstrap

element ui中table表格中表头自适应宽度

在table中表头经常因为文字过长导致换行展示,一定也不美观,但是给每列都加上width会很麻烦,这个时候我们利用render-header的方式进行

html

<el-table style="width:100%" height="200px">
    <el-table-column
        v-for = "col of tableColumn"
        :label="col.label"
        :prop="col.prop"
        :render-header="labelHeader"
        show-overflow-tooltip>
    </el-table-column>
</el-table>

js

tableColumn[
    {
        label:'shouzsfd',
        prop:'da'
    },
    {
        label:'shoufdsfsfzsfd',
        prop:'da2'
    },
    {
        label:'shsfdfsdfouzsfd',
        prop:'da3'
    },
    {
        label:'shfsfdfouzsfd',
        prop:'da4'
    },
    
]

methods:{
    labelHead(h,{ column }){
        //定义参数
        let realWidth = 0
        //获取这个表格中所有的列选项文字内容列如(<span>shsfdfsdfouzsfd</span>等所有的)
        let span = document.createElement('span')
        //将<span></span>标签去掉获取单独的文字内容
        span.innerText = column.label
        //临时插入document
        document.body.appendChild(span)
        //获取标签的宽度并且有一些padding等添加20
        realWidth = span.getBoundingClientRect().width + 20
        column.minWidth = realWidth
        //移除document中的span
        document.body.removeChild(span)
        return h('span',column.label)
    }

注意是一定不要忘记给表格添加高度我当时没有添加高度就一直不管用(看个人是否需要添加有的不需要添加就没有报错)

;