🍀封装个指令实现复制内容到剪切板上
核心代码
import { ElMessage } from 'element-plus'
function copyToClipboard(textToCopy) {
// navigator clipboard 需要 https 等安全上下文
if (navigator.clipboard && window.isSecureContext) {
return navigator.clipboard.writeText(textToCopy)
}
// 兼容性处理
const textArea = document.createElement('textarea')
textArea.value = textToCopy
textArea.style.position = 'absolute'
textArea.style.opacity = '0'
textArea.style.left = '-9999px'
textArea.style.top = '-9999px'
document.body.appendChild(textArea)
textArea.focus()
textArea.select()
return new Promise((resolve, reject) => {
document.execCommand('copy') ? resolve('复制成功') : reject('复制失败')
textArea.remove()
})
}
export default {
mounted(el, binding) {
el.dataset.value = binding.value
el.addEventListener('click', async () => {
console.info('el.dataset.value', el.dataset.value)
try {
await copyToClipboard(el.dataset.value)
// 可以在这里添加复制成功的提示
ElMessage.success('复制成功')
} catch (err) {
console.error('Failed to copy text: ', err)
}
})
el.classList.add('copy-btn')
},
updated(el, binding) {
el.dataset.value = binding.value
},
unmounted(el) {
el.removeEventListener('click', () => {})
}
}
注册指令
directives.js
import copy from './copy'
export default app => {
app.directive('copy', copy)
}
main.js
import { createApp } from 'vue'
import App from './App.vue'
import installDirective from '@/directives'
const app = createApp(App)
installDirective(app)
使用
<el-card>
<adminTitle title="复制内容到剪切板" />
<div>
<span>{{ copyConent }}</span>
<el-icon>
<CopyDocument v-copy="copyConent" />
</el-icon>
</div>
<el-input v-model="copyedContent" placeholder="ctrl + v 粘贴"></el-input>
</el-card>
<script setup>
const copyConent = ref('这是一段待复制的内容')
const copyedContent = ref('')
</script>