vue实现复制插件
使用 vue-clipboard2 插件
安装插件:
npm install vue-clipboard2
在 main.js 中引入并注册:
import VueClipboard from 'vue-clipboard2'
Vue.use(VueClipboard)
在组件中使用:
<button v-clipboard:copy="textToCopy">复制文本</button>
使用原生 document.execCommand
创建自定义指令:
Vue.directive('copy', {
bind(el, { value }) {
el.$value = value
el.handler = () => {
const textarea = document.createElement('textarea')
textarea.value = el.$value
document.body.appendChild(textarea)
textarea.select()
document.execCommand('Copy')
document.body.removeChild(textarea)
}
el.addEventListener('click', el.handler)
},
unbind(el) {
el.removeEventListener('click', el.handler)
}
})
模板中使用:
<button v-copy="textToCopy">复制</button>
使用 Clipboard API
现代浏览器方法:
methods: {
async copyText(text) {
try {
await navigator.clipboard.writeText(text)
console.log('复制成功')
} catch (err) {
console.error('复制失败:', err)
}
}
}
封装为通用组件
创建 CopyButton.vue:
<template>
<button @click="handleCopy">
<slot>复制</slot>
</button>
</template>
<script>
export default {
props: {
text: {
type: String,
required: true
}
},
methods: {
async handleCopy() {
try {
await navigator.clipboard.writeText(this.text)
this.$emit('copied')
} catch {
const textarea = document.createElement('textarea')
textarea.value = this.text
document.body.appendChild(textarea)
textarea.select()
document.execCommand('copy')
document.body.removeChild(textarea)
this.$emit('copied')
}
}
}
}
</script>






