双击复制剪切板 复制剪切板

方法一

vue插件

npm install --save vue-clipboard2

引入

import Vue from 'vue'
import VueClipboard from 'vue-clipboard2'
 
Vue.use(VueClipboard)

方法执行

clickCopy() {
    this.$copyText("www.baidu.com").then(
      res => {
        console.log(res);
        this.$toast("已成功复制,可直接去粘贴");
      },
      err => {
        this.$toast("复制失败");
      }
    );
  }

方法二

原始写法 弃用了

<template>
  <div id="app">
    <p
      v-for="item in items"
      :key="item"
      @dblclick="copyToClipboard(item)"
    >
      {{ item }}
    </p>
  </div>
</template>
 
<script>
export default {
  name: 'App',
  data() {
    return {
      items: ['这是第一条信息', '这是第二条信息', '这是第三条信息']
    };
  },
  methods: {
    copyToClipboard(text) {
      const textArea = document.createElement('textarea');
      textArea.value = text;
 
      // 防止元素显示在屏幕上
      textArea.style.position = 'fixed';
      textArea.style.top = '0';
      textArea.style.left = '0';
      textArea.style.width = '2em';
      textArea.style.height = '2em';
      textArea.style.padding = '0';
      textArea.style.border = 'none';
      textArea.style.outline = 'none';
      textArea.style.boxShadow = 'none';
      textArea.style.background = 'transparent';
      
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
 
      try {
        const successful = document.execCommand('copy');
        console.log(successful ? 'Copy successful' : 'Copy failed');
      } catch (err) {
        console.error('Oops, unable to copy', err);
      }
 
      document.body.removeChild(textArea);
    }
  }
};
</script>

 

posted @ 2024-03-14 15:59  ThisCall  阅读(1)  评论(0编辑  收藏  举报