<a-table>行数据增加点击事件并获取点击行的数据+自定义button按事件
先看代码:
在 Ant - Design - Vue 的<a - table>组件中,通过customRow属性可以为表格的每一行添加自定义的行为和样式。当设置customRow为一个返回包含onClick函数的对象的函数时,实际上是在为每一行添加一个点击事件监听器。
在a-table标签中添加 :customRow=“rowClick” 自定义样式
然后在ts中定义rowClick方法,方法内使用onClick监听点击事件,
实现的基本思路便是,在自定义样式中自定义监听事件,形参record是我们点击获取的行数据。
DataItem 是我自己定义的数据类型接口。
以前是面向对象,现在是面向接口,接口大于一切,规范化编程。
<template>
<a-table
bordered
:columns="columns"
:data-source="data"
:scroll="{ x: 1500, y: 300 }"
:customRow="rowClick"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'operation'">
<div style="display: flex; align-items: center">
<a-button @click="handleEdit(record)" style="background-color: #598db4">修改</a-button>
<a-button @click="handleDelete(record)" style="background-color: #598db4">删除</a-button>
</div>
</template>
</template>
</a-table>
</template>
<script setup lang="ts">
import type { TableColumnsType } from 'ant-design-vue';
const columns: TableColumnsType = [
{ title: 'Name', width: 100, dataIndex: 'name', key: 'name'},
{ title: 'Age', width: 100, dataIndex: 'age', key: 'age'},
{
title: 'Action',
key: 'operation',
fixed: 'right',
align: 'center',
width: 200,
},
];
interface DataItem {
key: number;
name: string;
age: number;
}
const data: DataItem[] = [
{
key: 1,
name: 'John',
age: 32,
},
{
key: 1,
name: 'John',
age: 32,
},
];
const handleEdit = (record: DataItem) => {
const rec = record;
console.log(rec);
}
const handleDelete = (record: DataItem) => {
const rec = record;
console.log(rec);
}
const rowClick = (record: DataItem ) => {
return {
onClick: () => {
const rec = record;
console.log(rec)
},
}
}
</script>
<style scoped>
</style>