vue中使用clipboard复制文本
新建一个clipboard.js来存放clipboard方法
npm install clipboard --save
import Vue from 'vue'
import Clipboard from 'clipboard'
// 文本复制
function copySuccess() {
Vue.prototype.$message({
type: 'success',
message: '复制文本成功',
duration: 1500
})
}
function copyFail() {
Vue.prototype.$message({
message: '该浏览器不支持自动复制',
type: 'warning'
})
}
export default function copyText(text,e) {
const clipboard = new Clipboard(e.target, {
text: () => text
})
clipboard.on('success', () => {
clipboardSuccess()
// 释放内存
clipboard.destroy()
})
clipboard.on('error', () => {
// 不支持复制
clipboardError()
// 释放内存
clipboard.destroy()
})
// 解决第一次点击不生效的问题,如果没有,第一次点击会不生效
clipboard.onClick(e)
}
然后在vue中直接导入使用即可
import copyText from '@/utils/clipboard'
<div @click="textCopy('123',$event)">text</div>
// 复制文本
textCopy(text,event) {
copyText(text,event)
},
以上就完成了文本复制的操作
-----------------------------------------------------------------------------------------------------------------------------------------------
以下提供另一种不需要使用clipboard插件来实现复制的方法
批量注册组件指令,新建directives/index.js文件
import copy from './copy' const directives = { copy } const install = function (Vue) { Object.keys(directives).forEach((key) => { Vue.directive(key, directives[key]) }) } export default install
新建directives/copy.js文件
/* * 实现思路 * 动态创建 textarea 标签,并设置 readOnly 属性及移出可视区域 * 将要复制的值赋给 textarea 标签的 value 属性,并插入到 body * 选中值 textarea 并复制 * 将 body 中插入的 textarea 移除 * 在第一次调用时绑定事件,在解绑时移除事件 */ const copy = { bind(el, binding) { const value = binding.value el.$value = value const abc = () => { if (!el.$value) { // 值为空时 console.log('无复制内容!') return } // 动态创建textarea标签 const textarea = document.createElement('textarea') // 将该textarea设为readonly防止ios下自动唤起键盘,同时将textarea移出可视区域 textarea.readOnly = 'readonly' textarea.style.position = 'absolute' textarea.style.left = '-9999px' // 将要copy的值赋值给textarea标签的value属性 textarea.value = el.$value // 将textarea插入到body中 document.body.appendChild(textarea) // 选中值 textarea.select() // 将选中的值复制并赋值给result const result = document.execCommand('Copy') if (result) { console.log('复制成功!') } document.body.removeChild(textarea) } // 绑定点击事件 el.addEventListener('click', abc) }, // 当传进来的值更新的时候触发 componentUpdated(el, { value }) { el.$value = value }, // 指令与元素解绑的时候,移除事件绑定 unbind(el) { el.removeEventListener('click', el.handler) } } export default copy
在main.js中导入文件
import Vue from 'vue' import Directives from '@/directives/index' Vue.use(Directives)
使用方法,点击p标签就可以实现复制
<template>
<div>
<p v-copy="copyText">复制</p>
</div>
</template>
<script>
export default {
name: 'Test',
data() {
return {
copyText: 'a copy directives'
}
},
methods: {}
}
</script>
<style lang="scss" scoped>
</style>

浙公网安备 33010602011771号