vue点击按钮复制文本粘贴

原链接:

vue实现复制粘贴的两种形式 - 前端极客 - 博客园

vue点击按钮复制文本粘贴 - 知乎

一、引入clipboard.js,方法如下:

1.安装clipboard:npm install clipboard

2.src/utils/clipboard.js

import Vue from 'vue'
import Clipboard from 'clipboard'

function clipboardSuccess() {
  console.log('success')
  Vue.prototype.$message({
    message: 'Copy successfully',
    type: 'success',
    duration: 1500
  })
}

function clipboardError() {
  console.log('error')
  Vue.prototype.$message({
    message: 'Copy failed',
    type: 'error'
  })
}

export default function handleClipboard(text, event) {
  const clipboard = new Clipboard(event.target, {
    text: () => text
  })
  clipboard.on('success', () => {
    clipboardSuccess()
    clipboard.off('error')
    clipboard.off('success')
    clipboard.destroy()
  })
  clipboard.on('error', () => {
    clipboardError()
    clipboard.off('error')
    clipboard.off('success')
    clipboard.destroy()
  })
  clipboard.onClick(event)
}

3.vue代码

<template>
    <div class="app-container">
      <el-tabs>
       <el-tab-pane label="直接使用剪切板">
         <div class="el-tab-pane" >
           <el-input   v-model="inputData"    style='width:400px;'></el-input>
           <el-button    @click="handleCopy(inputData,$event)">复制</el-button>
         </div>
       </el-tab-pane>
      </el-tabs>
    </div>
</template>
<script>
  import clip from '@/utils/clipboard'
  export default {
        name: "index",
        data(){
          return {
            inputData:""
          }
        },
      methods:{
        handleCopy(text, event) {
          clip(text, event)
          console.log('clicp')
        }
      }
    }
</script>

<style scoped>

</style>



<el-tab-pane label="使用封装的剪切指令v-directive">
  <div class="el-tab-pane" >
    <el-input     style='width:400px;'></el-input>
    <el-button>复制</el-button>
  </div>
</el-tab-pane>

二、通过构建input实列的方法,不需要引入插件

<span
            @click="copywxtap"
            v-text="datalist.product_name"
            ref="copytext"
          ></span>

在methods方法里面使用:

 copywxtap() {
      this.copyContent = this.$refs.copytext.innerText;//也可以直接写上等于你想要复制的内容
      var input = document.createElement("input"); // 直接构建input
      input.value = this.copyContent; // 设置内容
      console.log(input.value);
      document.body.appendChild(input); // 添加临时实例
      input.select(); // 选择实例内容
      document.execCommand("Copy"); // 执行复制
      document.body.removeChild(input); // 删除临时实例
      alert("复制成功");
    },

大功告成,欢迎指点

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值