动态表头 el-table el-dropdown el-checkbox

需求类似下图
动态表头 el-table el-dropdown el-checkbox_第1张图片

  1. 样式
    主体是表格 el-table,最后一个表头是按钮,用插槽来实现
    表头字段用下拉菜单实现 el-dropdown
    多选功能用 el-checkbox 来实现

    <template slot="header" slot-scope="scope">
    	<el-dropdown :hide-on-click="false" :index="scope.row">
    		<el-button icon="el-icon-more">el-button>
    		<el-dropdown-menu slot="dropdown">
    			<el-dropdown-item>
    				<el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选el-checkbox>
    			el-dropdown-item>
    			<el-checkbox-group v-model="checkboxs" @change="handleCheckedCitiesChange">
    				<el-dropdown-item v-for="item in headers" :key="item.prop">
    					<el-checkbox :label="item.label" @change="headerChange(item)">{{item.label}}el-checkbox>
    				el-dropdown-item>
    	  		el-checkbox-group>
    		el-dropdown-menu>
    	el-dropdown>
    template>
    
    headers: [
    	{prop:"data",label:"日期",index:"0"},
    	{prop:"name",label:"名字",index:"1"},
    	{prop:"address",label:"地址",index:"2"}
    ], // 总表头数据
    header:[], // 展示的表头
    checkboxs: [], // checkbox-group 数据
    checkAll: false,
    isIndeterminate: true
    
  2. 逻辑

    默认全选的状态下,在 mounted 将 headers 数据赋值给 header,将 headers 的 lable 赋值给checkboxs

    resetChecked() {
    	this.checkboxs = []
    	this.header = []
    	this.$nextTick(function () {
    		this.headers.map(item => {
    			this.header.push({
    				prop: item.prop,
    				label: item.label,
    				index: item.index
    			});
    			this.checkboxs.push(item.label);
    		})
    		this.isIndeterminate = false;
    		this.checkAll = true
    	})	
    }
    

    全选和多选请参照 el-checkbox

    	  handleCheckAllChange(val) {
            this.checkedCities = val ? cityOptions : [];
            if (checkedCities.length > 0) {
            	this.resetChecked()
            } else {
            this.checkboxs = []
            this.header = []
            this.isIndeterminate = false;
          },
          handleCheckedCitiesChange(value) {
            let checkedCount = value.length;
            this.checkAll = checkedCount === this.headers.length;
            this.isIndeterminate = checkedCount > 0 && checkedCount < this.headers.length;
          }
    

    表头动态展示+排序

    headerChange(value, index) {
    	let checkedIndex = this.header.findIndex( item => item.prop === value.prop);
    	if (checkedIndex  != -1) {
    		this.header.splice(checkedIndex, 1)
    	} else {
    		this.header.push(value)
    		this.header.sort(this.sortFunc("index"))
    	}
    },
    sortFunc(i) {
    	return funcyion (a,b) {
    		return a[i] - b[i];
    	}
    }
    
  3. 注意

    插槽的scope别忘了写

你可能感兴趣的:(vue,vue.js,elementui,前端,javascript)