Vue el-table 表格第一列序号与复选框hover切换

前言

项目中用vue element el-table , 表格的第一列为鼠标经过时切换显示序号与复选框 , 不影响当前行的点击事件 , 如跳转详情等操作

老规矩,先上效果图

Vue el-table 表格第一列序号与复选框hover切换_第1张图片

HTML

<el-table
      ref="table"
      :data="tableData"
      style="width: 100%"
      border
      stripe
      @cell-mouse-enter="cellEnter"
      @cell-mouse-leave="cellLeave"
      @selection-change="handleSelectionChange"
      @row-click="toDeatils"
    >
      <el-table-column type="selection" width="50" align="left">
        <template #default="{ row, $index }">
          <div
            v-if="columnCheckedId == row.id || checkedList[$index]"
            @click.stop
          >
            <el-checkbox
              v-model="checkedList[$index]"
              @change="cellCheckbox(row, $index)"
            ></el-checkbox>
          </div>
          <span v-else>{{ $index + 1 }}</span>
        </template>
      </el-table-column>
      <!-- 如有操作列 ↓-->
    </el-table>

JS

data() {
    return {
      columnCheckedId: '',
      tableData: [], //table数据
      multipleSelection: [], //table多选数据
      checkedList: [], //table多选选中数据
    }
  },
  methods:{
	  	handleSelectionChange(val) {
	      this.multipleSelection = val
	      if (this.multipleSelection.length == this.tableData.length) {
	        this.multipleSelection.forEach((item, index) => {
	          this.checkedList[index] = true
	        })
	      }
	      if (this.multipleSelection.length == 0) {
	        this.checkedList = []
	      }
	      this.$emit('selectList', this.multipleSelection)
	  	},
	    //鼠标移入表格当前行
	    cellEnter(row, column, cell, event) {
	      this.columnCheckedId = row.id
	    },
	    // 鼠标移出表格当前行
	    cellLeave(row, column, cell, event) {
	      this.columnCheckedId = ''
	    },
	    // 选中与否塞数据
	    cellCheckbox(row, index) {
	      if (this.checkedList[index]) {
	        this.$refs.table.toggleRowSelection(row, true)
	      } else {
	        this.$refs.table.toggleRowSelection(row, false)
	      }
	    },
  }

你可能感兴趣的:(前端踩坑合集,vue.js,javascript,前端)