Vue:如何实现一个具有复制功能的文字按钮?


实现一个具有复制功能的文字按钮

通过点击按钮实现指定文字的复制功能。

文章目录


1.效果图


2.关键代码

html 复制代码
#template
<span id="copycontent">{{web_url}}</span><button style="position: relative; top: -2px;left: 5px;" variant="text" theme="success" @click="copyClick">复制</button>
javascript 复制代码
#script
methods: {
        copyClick(){
            var input = document.createElement('input'); 
		        document.body.appendChild(input);
		        var content = document.querySelector('#copycontent').innerHTML;
		        input.setAttribute('value', content);
		        input.select();
		        if (document.execCommand('copy')) {
					document.execCommand('copy');
                    this.$message.success(this.$t('copy_succ'));
		        }
		        document.body.removeChild(input);
        },
}

总结

通过操作DOM 使用 document.execCommand('copy') 是用于复制选中文本到剪贴板的命令。但是document.execCommand 存在兼容性问题,部分浏览器可能已经不再支持。

相关推荐
QQ1__81151751519 分钟前
Spring boot名城小区物业管理系统信息管理系统源码-SpringBoot后端+Vue前端+MySQL【可直接运行】
前端·vue.js·spring boot
钛态20 分钟前
前端微前端架构:大项目的救命稻草还是自找麻烦?
前端·vue·react·web
一粒黑子21 分钟前
【实战解析】阿里开源 PageAgent:纯前端 GUI Agent,一行JS让网页支持自然语言操控
前端·javascript·开源
独角鲸网络安全实验室23 分钟前
2026微信小程序抓包全解析:从实操落地到合规风控,解锁前端调试新范式
前端·微信小程序·小程序·抓包·系统代理绕过·https证书严格校验·进程隔离
紫微AI23 分钟前
前端文本测量成了卡死一切创新的最后瓶颈,pretext实现突破了
前端·人工智能·typescript
GISer_Jing23 分钟前
AI前端(From豆包)
前端·aigc·ai编程
IT枫斗者23 分钟前
前端部署后如何判断“页面是不是最新”?一套可落地的版本检测方案(适配 Vite/Vue/React/任意 SPA)
前端·javascript·vue.js·react.js·架构·bug
测试修炼手册23 分钟前
[测试技术] 深入理解 JSON Web Token (JWT)
前端·json
AI老李26 分钟前
2026 年 Web 前端开发的 8 个趋势!
前端
里欧跑得慢28 分钟前
15. Web可访问性最佳实践:让每个用户都能平等访问
前端·css·flutter·web