el-table 手动对选中的行排序
时间: 2023-10-06 21:09:14 浏览: 50
如果你想手动对 el-table 中选中的行进行排序,可以按照以下步骤操作:
1. 获取当前选中的行数据和排序方式。
2. 对选中的行数据进行排序。可以使用 JavaScript 中的 sort() 方法或 Lodash 库中的 orderBy() 方法等。
3. 根据排序方式,对 el-table 中的数据进行更新。可以使用 el-table 组件中的 $refs 属性获取到 el-table 实例,然后调用实例的 setTableData() 方法来更新数据。
下面是一个简单的示例代码,仅供参考:
```html
<el-table ref="table" :data="tableData" :row-key="row => row.id" @row-click="handleRowClick">
<el-table-column prop="id" label="ID"></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>
```
```javascript
export default {
data() {
return {
tableData: [
{ id: 1, name: 'Alice', age: 20 },
{ id: 2, name: 'Bob', age: 25 },
{ id: 3, name: 'Charlie', age: 30 },
{ id: 4, name: 'David', age: 35 }
],
selectedRows: [],
sortKey: null,
sortOrder: null
}
},
methods: {
handleRowClick(row) {
this.$refs.table.toggleRowSelection(row)
this.selectedRows = this.$refs.table.selection
},
handleSort() {
if (this.sortKey && this.sortOrder) {
this.selectedRows.sort((a, b) => {
const sortVal = this.sortOrder === 'asc' ? 1 : -1
if (a[this.sortKey] < b[this.sortKey]) {
return -sortVal
} else if (a[this.sortKey] > b[this.sortKey]) {
return sortVal
} else {
return 0
}
})
const newData = this.tableData.map(row => {
if (this.selectedRows.indexOf(row) > -1) {
return this.selectedRows.shift()
} else {
return row
}
})
this.$refs.table.setTableData(newData)
}
}
}
}
```
在上述示例代码中,我们定义了一个 el-table 组件,并且监听了它的 row-click 事件,以便获取选中的行数据。然后,我们定义了一个 handleSort() 方法,该方法会根据 sortKey 和 sortOrder 对选中的行数据进行排序,并更新 el-table 中的数据。注意,我们需要使用 $refs 属性获取到 el-table 实例,以便调用 setTableData() 方法来更新数据。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)