原链接:
一、引入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("复制成功");
},
大功告成,欢迎指点