vue-directive__自定义指令
1.复制
/**
* v-copy
* 复制某个值至剪贴板
* 接收参数:string类型/Ref<string>类型/Reactive<string>类型
*/
import type { Directive, DirectiveBinding } from "vue";
import { ElMessage } from "element-plus";
interface ElType extends HTMLElement {
copyData: string | number;
__handleClick__: any;
}
const copy: Directive = {
mounted(el: ElType, binding: DirectiveBinding) {
el.copyData = binding.value;
el.addEventListener("click", handleClick);
},
updated(el: ElType, binding: DirectiveBinding) {
el.copyData = binding.value;
},
beforeUnmount(el: ElType) {
el.removeEventListener("click", el.__handleClick__);
}
};
// 复制到剪贴板:旧方法(已弃用)
// function handleClick(this: any) {
// const input = document.createElement("input");
// input.value = this.copyData.toLocaleString();
// document.body.appendChild(input);
// input.select();
// document.execCommand("Copy");
// document.body.removeChild(input);
// ElMessage({
// type: "success",
// message: "复制成功"
// });
// }
// 复制到剪贴板:新方法
function handleClick(this: any) {
navigator.clipboard.writeText(this.copyData.toLocaleString()).then(() => {
ElMessage({
type: "success",
message: "复制成功"
});
}, () => {
ElMessage({
type: "error",
message: "复制失败"
});
});
}
export default copy;
标签:__,el,vue,自定义,handleClick,binding,copyData,input
From: https://www.cnblogs.com/miyagi-jiye/p/16787259.html