JS实现一键复制文本

发布时间 2023-12-15 08:08:42作者: ^Mao^

背景

实现对table中的某一列文本内容进行复制

代码

需求:表格中只有"姓名"列可以复制,其他列不能复制

<template>
  <div class="app">
    <h1>App Page</h1>
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="date" label="日期" width="180"> </el-table-column>
      <el-table-column prop="name" label="姓名" width="180" class-name="can-select">
      </el-table-column>
      <el-table-column prop="address" label="地址"> </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableData: [
        {
          date: "2016-05-02",
          name: "小明",
          address: "上海市普陀区金沙江路 1518 弄",
        },
        {
          date: "2016-05-04",
          name: "小红",
          address: "上海市普陀区金沙江路 1517 弄",
        },
        {
          date: "2016-05-01",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1519 弄",
        },
        {
          date: "2016-05-03",
          name: "张三",
          address: "上海市普陀区金沙江路 1516 弄",
        },
      ],
    };
  },
  mounted() {
    const table = document.querySelector(".el-table__body-wrapper");

    const allNames = this.tableData.map((item) => item.name);
    table.onmouseup = async () => {
      const selection = window.getSelection().toString();
      if (!selection) return;
      console.log(selection);

      const selectionArr = selection.split(/\n/);
      const result = [];
      selectionArr.forEach((s) => {
        if (allNames.includes(s)) {
          result.push(s);
        }
      });
      const copyContent = result.join(",");
      await navigator.clipboard.writeText(copyContent);
      this.$notify({
        title: "成功",
        message: "姓名复制成功",
        type: "success",
      });
    };
  },
};
</script>

<style lang="less" scoped>
/deep/.el-table__body-wrapper {
  user-select: none;
}

/deep/.can-select .cell {
  user-select: text;
}
</style>

效果图