Element UI el-table 默认选中行设置教程
Element UI el-table 设置默认选中内容
在使用 Element UI 的 el-table 组件时,我们可能需要设置默认选中行。以下介绍两种方法来实现该功能。
1. 使用 v-model 绑定选中行数据
使用 v-model 指令可以绑定选中行的数据。例如:
<el-table v-model='selectedRows' :data='tableData' @selection-change='handleSelectionChange'>
<el-table-column type='selection'></el-table-column>
<el-table-column prop='name' label='Name'></el-table-column>
<el-table-column prop='age' label='Age'></el-table-column>
</el-table>
在 data 中定义 selectedRows 数组,并在 methods 中定义 handleSelectionChange 方法来处理选中行的变化:
data() {
return {
selectedRows: [],
tableData: [
{ name: 'John', age: 26 },
{ name: 'Jane', age: 28 },
{ name: 'Bob', age: 30 }
]
}
},
methods: {
handleSelectionChange(selectedRows) {
this.selectedRows = selectedRows
}
}
2. 使用 ref 获取 el-table 实例
使用 ref 属性可以获取 el-table 实例,然后调用其 select 方法。例如:
<el-table ref='table' :data='tableData' @row-click='handleRowClick'>
<el-table-column prop='name' label='Name'></el-table-column>
<el-table-column prop='age' label='Age'></el-table-column>
</el-table>
在 methods 中定义 handleRowClick 方法来处理行点击事件:
methods: {
handleRowClick(row) {
this.$refs.table.clearSelection()
this.$refs.table.toggleRowSelection(row)
}
}
在 handleRowClick 方法中,首先调用 clearSelection 方法来清除所有选中行,然后调用 toggleRowSelection 方法来选中当前行。
原文地址: https://www.cveoy.top/t/topic/oth7 著作权归作者所有。请勿转载和采集!