1、安装插件

npm install clipboard --save

2、复制纯文本

<template>
    <div>
        <a class="clip-btn" 
           data-clipboard-text="'hello world'" 
           href="javascript:void(0);">复制文本</a>
    </div>
<template>

<script>
import Clipboard from 'clipboard';
export default {
    name: 'index',
    data(){
        return {
           btnCopy:'',
        } 
    }    
    mounted() {
        this.btnCopy = new Clipboard('.clip-btn')
        this.btnCopy.on('success', (e) => {
            console.log('Text:', e.text)
            this.$message({message: '复制成功', type: 'success'})
            e.clearSelection()
        })
    },
    beforeDestroy () {        
        // 销毁clipboard        
        if (this.btnCopy && this.btnCopy.destroy) {            
            this.btnCopy.destroy()        
        }
    }}
</script>

3、复制富文本的内容(包括文本和图片)

<template>
    <div>
        <a class="clip-btn" 
           data-clipboard-target="#copytext" 
           href="javascript:void(0);">复制文本</a>
        <div id="copytext">
            <p>我是富文本</p>
            <img src="../../1.png"/>
        </div>
    </div>
<template>

<script>
import Clipboard from 'clipboard';
export default {
    name: 'index',
    data() {
        return {
           btnCopy:'',
        }
    }
    mounted() {
        this.btnCopy = new Clipboard('.clip-btn',{
            target: function(trigger) {
                return document.getElementById('copytext');
            }
        })
        this.btnCopy.on('success', (e) => {
            console.log('Text:', e.text)
            this.$message({message: '复制成功', type: 'success'})
            e.clearSelection()
        })
    },
    beforeDestroy () {   
        // 销毁clipboard
        if (this.btnCopy && this.btnCopy.destroy) {  
            this.btnCopy.destroy()
        }
    }}
</script>

 

 

 

Logo

前往低代码交流专区

更多推荐