ElementUi Table复选框回显

发布于:2024-06-08 ⋅ 阅读:(164) ⋅ 点赞:(0)
 <el-table ref="multipleTable" :data="tableData" @selection-change="handleSelectionChange">
   <el-table-column type="selection" width="55" :reserve-selection="true" show-overflow-tooltip>
   </el-table-column>
   <el-table-column prop="name" label="Name"></el-table-column>
   <el-table-column prop="age" label="Age"></el-table-column>
   <el-button @click="toggleSelection">Toggle Selection</el-button>
 </el-table>
<script>
export default {
  data() {
    return {
      tableData: [
        { id: 1, name: 'John', age: 30 },
        { id: 2, name: 'Doe', age: 25 },
        { id: 3, name: 'Smith', age: 35 }
      ]
    };
  },
  methods: {
    toggleSelection() {
      const rowToToggle = this.tableData[0]; // 假设切换第一行的选中状态
      const selected = !rowToToggle.selected; // 切换选中状态
      this.$refs.multipleTable.toggleRowSelection(rowToToggle, selected);
    }
  }
};
</script>

如果想要在初始化的时候就默认勾选,需要用到this.$nextTick,可以确保在 DOM 更新后执行,以便正确设置初始的选中状态。否则直接用的话报错Error in v-on handler: "TypeError: Cannot read properties of undefined (reading 'toggleRowSelection')"

mounted() {
  // 模拟初始化时默认勾选第一行和第二行
  this.$nextTick(() => {
    this.$refs.multipleTable.toggleRowSelection(this.tableData[0], true);
    this.$refs.multipleTable.toggleRowSelection(this.tableData[1], true);
 });
}

监听了selection-change事件,想要在手动勾选的时候执行某些操作

handleSelectionChange(vals) {
	console.log(vals)
}

会发现,初始化的时候由于执行了this.$refs.multipleTable.toggleRowSelection方法,导致selection-change也会自动触发。实际中要想把这两者分开来,可以加一个标识字init来区分。

<script>
export default {
  data() {
    return {
      tableData: [
        { id: 1, name: 'John', age: 30 },
        { id: 2, name: 'Doe', age: 25 },
        { id: 3, name: 'Smith', age: 35 }
      ],
      init: true
    };
  },
  mounted() {
    this.tableData = this.tableData.map((v, vIndex) => {
	...
	that.$nextTick(() => {
	  that.$refs.multipleTable.toggleRowSelection(v, true);
	  if (...) { // 初始化执行完时的判断条件
	    setTimeout(() => {
	      that.init = false
	   }, 0)
	 }
	})
  },
  methods: {
    handleSelectionChange(vals) {
	   console.log(vals)
	   if(this.init) {
	   	 console.log('初始化时触发的')
	   } else {
	   	console.log('手动勾选时触发的')
	   }
    }
  }
</script>

网站公告

今日签到

点亮在社区的每一天
去签到