1、引入clipboard

npm install clipboard --save

2、使用的页面引入

// 剪切板插件
import Clipboard from "clipboard";

3、有两种实现方式(分为固定的数据和列表循环数据动态化)

(1)第一种

页面内容为:

        <div class="list">
          <p class="name">公司名称</p>
          <p class="value">
            <span>{{companyName }}</span>
            <v-button
              mini
              plain
              type="primary"
              class="copy_btn"
              id="companyName"
              :data-clipboard-text="companyName"
              @click.native="copyFn('#companyName', '公司名称')"
              >复制</v-button>
          </p>
        </div>

js代码为:

    copyFn(id, title) {
      let clipboard = new Clipboard(id);
      let _this = this;
      this.$nextTick(() => {
        clipboard.on("success", function(e) {
          _this.$showPosition(title + "已复制");
          clipboard.destroy();
        });
        clipboard.on("error", function(e) {
          console.log("不支持复制功能哦!");
          clipboard.destroy();
        });
      });
    }

(2)第二种

页面内容为:

            <div class="baseInfo_item" v-for="item,index in List" :key="index">
              <span>运单{{index+1}}:</span>
              <div class="right inline" :id="'copy-btn' + index" data-clipboard-action="copy"
                :data-clipboard-target="'#share-code'+index" @click="copyFn('#copy-btn' + index)">
                <span :id="'share-code' + index">{{item.no}}</span>
                <img class="copy-icon" src="../assets/images/prePay/copy-icon.png" />
              </div>
            </div>

js代码内容:

      copyFn(id) {
        let clipboard = new Clipboard(id);
        let _this = this;
        this.$nextTick(() => {
          clipboard.on('success', function (e) {
            _this.$toast("已复制");
            clipboard.destroy();
          });
          clipboard.on('error', function (e) {
            console.log('您的浏览器不支持点击复制');
            clipboard.destroy();
          });
        });
      }

 

4、原生javascript实现

    copy(text, e) {
      let ele = e.currentTarget
      if (ele) {
        let transfer = document.createElement('input')
        ele.appendChild(transfer)
        transfer.value = text 
        transfer.focus()
        transfer.select()
        if (document.execCommand('copy')) {
          document.execCommand('copy')
        }
        transfer.blur()
        console.log('已复制到剪切板')
        ele.removeChild(transfer)
      }
    }

 

posted on 2020-06-04 13:54  阿梅M  阅读(2458)  评论(1编辑  收藏  举报