js 实现复制的主要命令是 document.execCommand('copy'),只有在输入框中的内容被选择时执行此命令才有效。
但是一般情况下,我们想要复制的内容并不是输入框中的文字,这时我们把只要临时创建一个 input 元素,将想要复制的内容赋值给 input 的 value 属性,并让它 select,等执行完复制命令后再将其删除就可以了。
代码如下:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 
 | <button @click="copy">点击复制</button><p ref="p">hello world</p>
 
 <script>
 copy() {
 const val = this.$refs.p.innerText;
 const input = document.createElement('input');
 input.value = val;
 document.body.appendChild(input);
 input.select();
 if(document.execCommand('copy')) {
 input.remove();
 this.$message({
 type: 'success',
 message: '复制成功'
 });
 }
 }
 </script>
 
 |