tiantingrui / daily-harvest

记录每日收获
MIT License
2 stars 0 forks source link

vue3 基于 element-plus 编写自定义 hook 实现文本复制功能 #23

Open tiantingrui opened 2 years ago

tiantingrui commented 2 years ago

前置知识

  1. HTMLInputElement.select() : https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLInputElement/select
  2. document.execCommand : https://developer.mozilla.org/zh-CN/docs/Web/API/Document/execCommand

编写自定义hook - useCopy.ts

import { ElMessage } from "element-plus";

export const useCopy = (text: string) => {
  // 1. 创建输入框
  let input = document.createElement("input");
  // 2. 给输入框 value 赋值
  input.value = text;
  // 3. 追加到 body 里面去
  document.body.appendChild(input);
  // 4. 选择输入框的操作
  input.select();
  // 5. 执行复制操作
  document.execCommand("copy");
  // 6. 删除加入的输入框
  document.body.removeChild(input);
  // 7. 提示用户
  ElMessage.success("复制成功");
}