侧边栏壁纸
博主头像
搭建网站的历程博主等级

生命不息,折腾不止

  • 累计撰写 36 篇文章
  • 累计创建 4 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录
VUE

VUE点击复制文本组件

甘超良
2023-12-25 / 0 评论 / 0 点赞 / 11 阅读 / 2273 字

功能说明

很多时候,对于一些字段,需要提供方便快捷的复制功能,如 url地址等,可以把这个功能封装为一个vue组件。

代码

<template>
  <div class="flex items-center space-x-1" title="点击文本进行复制">
    <span ref="textRef" @click="handleClick" class="cursor-copy">{{ modelValue }}</span>
    <el-icon @click="handleClick" class="cursor-pointer"><CopyDocument /></el-icon>
  </div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { CopyDocument } from "@element-plus/icons-vue";
const props = defineProps<{
  modelValue: string;
}>();
const textRef = ref<HTMLElement>();

const handleClick = () => {
  if (textRef) {
    selectAllText();

    // 执行复制命令
    navigator.clipboard.writeText(props.modelValue).then(() => {
      ElMessage.success("复制成功");
    });
  }
};

const selectAllText = () => {
  // 全选文字
  let selection = window.getSelection();
  let range = document.createRange();
  range.selectNodeContents(textRef.value!);
  selection?.removeAllRanges();
  selection?.addRange(range);
};
</script>

依赖

  1. element-plus
  2. @element-plus/icons-vue
  3. vue3
0

评论区