1.需要写一个copy指令的js
import { Toast } from 'vant';
const vCopy = {
bind(el, { value }) {
el.$value = value;
el.handler = () => {
if (!el.$value) {
Toast.fail('无复制内容');
return;
}
const textarea = document.createElement('textarea');
textarea.readOnly = 'readonly';
textarea.style.position = 'absolute';
textarea.style.left = '-9999px';
textarea.value = el.$value;
document.body.appendChild(textarea);
textarea.select();
textarea.setSelectionRange(0, textarea.value.length);
const result = document.execCommand('Copy');
if (result) {
Toast.success('复制成功');
}
document.body.removeChild(textarea);
};
el.addEventListener('click', el.handler);
},
componentUpdated(el, { value }) {
el.$value = value;
},
unbind(el) {
el.removeEventListener('click', el.handler);
},
};
export default vCopy;
2.注册全局指令(可以全局注册,也可以局部注册)
import copy from "./utils/copy.js";
Vue.directive('copy',copy);
import copy from "./utils/copy.js";
directive(copy);
3.指令的使用
<p v-copy="'复制的内容'">copy</p>
|