上周产品经理小张又双叒叕提了个需求:"这个优惠码要让用户能一键复制啊!" 🤦♂️ 作为前端er,这种需求简直像每天要喝水一样常见——订单号、邀请码、分享链接... 用户可不想手动选择老半天还复制失败,今天我们就来彻底搞定这个"小"功能!
先上最简单的实现方案,适合Vue 2/3通用:
// 在methods中 copyText(text) { const textarea = document.createElement('textarea') textarea.value = text document.body.appendChild(textarea) textarea.select() document.execCommand('copy') document.body.removeChild(textarea) this.$message.success('复制成功!') // 这里用了Element UI的提示 }
使用姿势:
<button @click="copyText('要复制的文本')">点击复制</button>
2025年了,当然要用更优雅的方式!(Vue 3专属✨)
import { ref } from 'vue' export function useClipboard() { const isCopied = ref(false) const copy = async (text) => { try { await navigator.clipboard.writeText(text) isCopied.value = true setTimeout(() => isCopied.value = false, 2000) return true } catch (err) { console.error('复制失败:', err) // 降级方案 const textarea = document.createElement('textarea') textarea.value = text document.body.appendChild(textarea) textarea.select() document.execCommand('copy') document.body.removeChild(textarea) isCopied.value = true return true } } return { isCopied, copy } }
组件中使用:
<script setup> import { useClipboard } from './useClipboard' const { isCopied, copy } = useClipboard() </script> <template> <button @click="copy('VIP2025优惠码')" :class="{ 'copied': isCopied }" > {{ isCopied ? '✓ 已复制' : '点击复制' }} </button> </template>
button { transition: all 0.3s ease; } button.copied { background-color: #4CAF50; color: white; }
import gsap from 'gsap' // 复制成功后 gsap.to(buttonRef, { scale: 1.05, duration: 0.2, yoyo: true, repeat: 1 })
// 有些安卓机需要特殊处理 if (/android/i.test(navigator.userAgent)) { textarea.setSelectionRange(0, 99999) } else { textarea.select() }
navigator.clipboard
在非安全上下文可能不可用// 检测是否是移动设备 const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) if (isMobile) { // 调起移动端键盘增强体验 textarea.readOnly = true textarea.focus({ preventScroll: true }) }
听说W3C正在讨论Clipboard API
的新提案,可能会新增:
不过现在还是先用稳当的方案吧!
✅ 基础方案:document.execCommand
✅ 现代方案:navigator.clipboard
✅ 必备:完善的错误处理和降级方案
✅ 加分项:视觉反馈和动画效果
✅ 特殊处理:移动端适配
下次产品再提复制需求,你可以优雅地说:"这个功能,我5分钟就能搞定!" 💪 记得复制本文档保存备用哦~(开玩笑的,收藏就好)
本文由 公良嘉淑 于2025-07-31发表在【云服务器提供商】,文中图片由(公良嘉淑)上传,本平台仅提供信息存储服务;作者观点、意见不代表本站立场,如有侵权,请联系我们删除;若有图片侵权,请您准备原始证明材料和公证书后联系我方删除!
本文链接:https://vps.7tqx.com/wenda/493608.html
发表评论