vue实现点击复制功能(无需安装库)
1.标签
<button v-copy="text">复制文本</button>
text是要复制的内容,在data函数中
2.在main.js中注册copy指令
Vue.directive('copy', {
bind: function(el, binding) {
el.$copy = function() {
const textarea = document.createElement('textarea');
textarea.value = binding.value;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('Copy');
document.body.removeChild(textarea);
}
el.addEventListener('click', el.$copy);
},
unbind: function(el) {
el.removeEventListener('click', el.$copy);
}
});
完成!