基于 Ant Design Vue 的表格点击行即可选中当前行
2023-12-11 18:13:54
前言
Ant Design Vue 是一个用于构建用户界面的 Vue.js 组件库,提供了丰富的组件和样式,帮助开发者快速构建高质量的 web 应用程序。Ant Design Vue 中的 Table 组件是一个功能强大的表格组件,支持多种功能,包括行选中、排序、过滤等。
封装 Table 组件
为了方便在不同的页面中使用,我们可以将 Table 组件封装成一个独立的组件。这样,我们就可以在需要的时候直接使用这个组件,而不用每次都重复编写代码。
<template>
<a-table
v-bind="$attrs"
v-on="$listeners"
:rowSelection="{
type: 'checkbox',
selectedRowKeys: selectedRowKeys,
onChange: onSelectChange
}"
>
<a-table-column
slot="selection"
width="50px"
align="center"
>
<template slot-scope="scope">
<a-checkbox
v-model="selectedRowKeys"
:value="scope.row.id"
/>
</template>
</a-table-column>
<!-- 其他列 -->
</a-table>
</template>
<script>
export default {
data() {
return {
selectedRowKeys: []
}
},
methods: {
onSelectChange(selectedRowKeys) {
this.selectedRowKeys = selectedRowKeys;
}
}
}
</script>
在这个组件中,我们使用了 attrs 和 listeners 来封装 Table 组件的功能。这使得我们可以在使用这个组件时,直接传递属性和事件监听器。
使用封装的 Table 组件
现在,我们可以使用封装的 Table 组件来创建可点击行即可选中当前行的表格。
<template>
<EncapsulatedTable
:data="data"
:columns="columns"
@selection-change="onSelectChange"
/>
</template>
<script>
import EncapsulatedTable from './EncapsulatedTable.vue'
export default {
components: {
EncapsulatedTable
},
data() {
return {
data: [
{
id: 1,
name: 'John Doe'
},
{
id: 2,
name: 'Jane Doe'
},
{
id: 3,
name: 'Peter Smith'
}
],
columns: [
{
title: 'ID',
dataIndex: 'id',
key: 'id'
},
{
title: 'Name',
dataIndex: 'name',
key: 'name'
}
]
}
},
methods: {
onSelectChange(selectedRowKeys) {
console.log('Selected row keys:', selectedRowKeys)
}
}
}
</script>
在这个组件中,我们使用了 EncapsulatedTable 组件。我们传递了 data 和 columns 属性,并监听了 selection-change 事件。
解决更新 selectedRowKeys 的问题
在使用封装的 Table 组件时,我们可能会遇到一个问题:当我们更新 selectedRowKeys 时,表格中的选中状态不会随之改变。这是因为 selectedRowKeys 是一个 prop,而不是一个 state。
为了解决这个问题,我们可以使用 watch 来监听 selectedRowKeys 的变化,并在变化时更新表格中的选中状态。
<script>
import EncapsulatedTable from './EncapsulatedTable.vue'
export default {
components: {
EncapsulatedTable
},
data() {
return {
data: [
{
id: 1,
name: 'John Doe'
},
{
id: 2,
name: 'Jane Doe'
},
{
id: 3,
name: 'Peter Smith'
}
],
columns: [
{
title: 'ID',
dataIndex: 'id',
key: 'id'
},
{
title: 'Name',
dataIndex: 'name',
key: 'name'
}
],
selectedRowKeys: []
}
},
watch: {
selectedRowKeys(val) {
this.$refs.table.setSelectedRowKeys(val)
}
},
methods: {
onSelectChange(selectedRowKeys) {
this.selectedRowKeys = selectedRowKeys
}
}
}
</script>
在这个组件中,我们使用了 watch 来监听 selectedRowKeys 的变化。当 selectedRowKeys 发生变化时,我们会调用 $refs.table.setSelectedRowKeys() 方法来更新表格中的选中状态。
结语
在本文中,我们介绍了如何在 Ant Design Vue 中创建可点击行即可选中当前行的表格。我们使用了 attrs 和 listeners 来封装 Table 组件的功能,并解决了更新 selectedRowKeys 的问题。