v-copy指令实现文本点击复制
document.execCommand方法MDN上显示已不再推荐使用该特性,可以使用clipboard.writeText实现,以下是在vue自定义指令v-copy实现复制
/**
* v-copy
* 复制值至剪贴板
*/
const copyText = {
mounted(el, binding) {
el.copyData = binding.value;
el.addEventListener('click', handleClick);
},
updated(el, binding) {
el.copyData = binding.value;
},
beforeUnmount(el) {
el.removeEventListener('click', el.__handleClick__);
},
};
async function handleClick() {
try {
await navigator.clipboard.writeText(this.copyData);
} catch (err) {
ElNotification({
message: '复制失败,请手动复制。',
type: 'warning',
});
}
ElNotification({
message: '成功复制到剪贴板!',
type: 'success',
});
}
export default copyText;
全局注册:
import copyText from '@/directive/copyText';
// 全局注册复制指令
app.directive('copy', copyText);
页面使用:
<el-input
v-model="outputData.value1"
disabled
placeholder="加密/解密后内容"
>
<template
v-if="outputData.value1"
#append
>
<el-button v-copy="outputData.value1">复 制</el-button>
</template>
</el-input>