vue通过插件v-clipboard复制文本
1、下载:
npm install --save v-clipboard
2、组件中引入(或者在main.js中全局引入)
import Vue from 'vue'
import Clipboard from 'v-clipboard'
Vue.use(Clipboard)
3、在按钮标签中加载指令 v-clipboard 绑定需要复制的值,通过 v-clipboard:success 绑定成功的回调,通过 v-clipboard:error 绑定失败的回调
<button v-clipboard="value" v-clipboard:success="handleSuccess" v-clipboard:error="handleError">点击复制</button>
data() {
return {
value: '指令:复制文本'
}
},
methods: {
handleSuccess() {
//成功
console.log('success', this.value)
this.$message.success('复制成功')
},
handleError() {
//失败
console.log('error', this.value)
}
}
完整代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<template> <div> <p class="margin-10">指令:复制文本</p> <div class="margin-10"> <button v-clipboard="value" v-clipboard:success="handleSuccess" v-clipboard:error="handleError">点击复制</button> </div> </div> </template> <script> import Vue from 'vue' import Clipboard from 'v-clipboard' Vue.use(Clipboard) export default { data() { return { value: '指令:复制文本' } }, methods: { handleSuccess() { //成功 console.log('success', this.value) this.$message.success('复制成功') }, handleError() { //失败 console.log('error', this.value) } } } </script> <style lang="less"> .margin-10 { margin: 10px; } </style>