表格中点击按钮复制当前行自定义表格内容
<template>
<div>
<!-- 表格 -->
<el-table :data="tableData" style="width: 100%">
<el-table-column label="姓名" prop="name"></el-table-column>
<el-table-column label="年龄" prop="age"></el-table-column>
<el-table-column label="城市" prop="city"></el-table-column>
<el-table-column label="操作">
<template #default="{ row }">
<el-button @click="copyRow(row)" size="small" type="primary">复制此行</el-button>
</template>
</el-table-column>
</el-table>
<!-- 提示信息 -->
<el-alert v-if="isCopied" title="文本已复制!" type="success" show-icon class="copy-alert"></el-alert>
</div>
</template>
<script setup>
import { ref } from "vue";
import { ElTable, ElTableColumn, ElButton, ElAlert } from "element-plus";
const tableData = ref([
{ name: "张三", age: 25, city: "北京" },
{ name: "李四", age: 30, city: "上海" },
{ name: "王五", age: 28, city: "广州" },
]);
const isCopied = ref(false);
// 获取表格列标题
const tableColumns = [
{ label: "姓名", prop: "name" },
{ label: "年龄", prop: "age" },
{ label: "城市", prop: "city" },
];
// 复制指定行的内容
const copyRow = (row) => {
let { name, city } = row;
let data = cloneDeep({
name,
city,
});
const tableColumns = [
{ label: "姓名", prop: "name" },
{ label: "城市", prop: "city" },
];
// 创建带表头的复制文本
const rowText = tableColumns.map((column) => `${column.label}:${data[column.prop]}`).join("\n"); // 每一列使用换行符分隔
// 使用浏览器的剪贴板 API进行复制
navigator.clipboard
.writeText(rowText)
.then(() => {
isCopied.value = true;
setTimeout(() => {
isCopied.value = false; // 3秒后清除复制提示
}, 3000);
})
.catch((err) => {
console.error("复制失败", err);
alert("复制失败");
});
};
</script>
<style scoped>
.copy-alert {
margin-top: 20px;
}
</style>