方案:找到textarea对象,获取焦点,选中textarea的所有内容,并调用document.execCommand("copy")
实现代码:
<template> <div> <textarea ref="letters"></textarea> <button @click="copyToClipboard(‘letters‘)">复制</button> </div> </template> <script> export default { data() { return { loading: false } }, created() { this.$nextTick(function () { this.$refs.letters.value = ‘用户名:张三\n性别:男\n电话号码:15812322222‘; }) }, methods: { //复制内容到粘贴板 copyToClipboard(elemRef) { let target; let succeed = false; if(this.$refs[elemRef]){ target = this.$refs[elemRef]; // 选择内容 let currentFocus = document.activeElement; target.focus(); target.setSelectionRange(0, target.value.length); // 复制内容 try { succeed = document.execCommand("copy"); alert("内容复制成功"); } catch (e) { succeed = false; } // 恢复焦点 if (currentFocus && typeof currentFocus.focus === "function") { currentFocus.focus(); } } return succeed; }, } } </script>
复制完成后,在记事本等编辑器中粘贴即可。
原文地址:https://www.cnblogs.com/yeqrblog/p/9571129.html
时间: 2024-10-09 17:17:21