vue常见问题之一键复制功能实现

发布于:2025-04-14 ⋅ 阅读:(19) ⋅ 点赞:(0)

有些场景下需要给用户提供自动复制的的功能,常用的复制功能实现方式使用Clipboard API或者就浏览器的回退方案。

基本实现方式

使用Clipboard API(推荐)

该种方式只能在https中或者本地localhost中使用,如果在其他环境下会有获取不到clipboard对象的问题。

async function copyToClipboard(text) {
  try {
    await navigator.clipboard.writeText(text);
    console.log('复制成功');
    return true;
  } catch (err) {
    console.error('复制失败:', err);
    return false;
  }
}

兼容旧浏览器的回退方案

function legacyCopy(text) {
  const textarea = document.createElement('textarea');
  textarea.value = text;
  textarea.style.position = 'fixed';
  textarea.style.opacity = '0';
  document.body.appendChild(textarea);
  textarea.select();
  
  try {
    const success = document.execCommand('copy');
    document.body.removeChild(textarea);
    return success;
  } catch (err) {
    console.error('传统复制方法失败:', err);
    return false;
  }
}

使用第三方组件

vue-clipboard3,当上面两种方案不能实现的时候使用第三方组件实现。

安装组件

yarn add vue-clipboard3

or

npm install --save vue-clipboard3

vue中使用组件

import clipBoard from 'vue-clipboard3'
let { toClipboard } = clipBoard();    // 一键复制
 
const apiKey = ref('020a7563.....43cd0');
// 一键复制
const handleCopy = async () => {
    try {
        await toClipboard(apiKey.value);
        ElMessage({
            message: 'Copy',
            type: 'success',
        })
    } catch (e) {
        ElMessage({
            message: e,
            type: 'error',
        })
    }
}

网站公告

今日签到

点亮在社区的每一天
去签到