新建一個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>