浏览代码

✨ 二次确认指令

晓晓晓晓丶vv 4 年之前
父节点
当前提交
151da6e995
共有 4 个文件被更改,包括 60 次插入0 次删除
  1. 14 0
      src/helper/index.ts
  2. 3 0
      src/plugins/install.ts
  3. 37 0
      src/plugins/vue-confirm.ts
  4. 6 0
      src/views/Page1.vue

+ 14 - 0
src/helper/index.ts

@@ -15,6 +15,20 @@ export const listener = (
 };
 
 /**
+ * 移除监听事件
+ * @param el
+ * @param cb
+ * @param type
+ */
+export const removeListener = (
+  el: HTMLElement | Element,
+  cb: Function,
+  type: string = "click"
+) => {
+  el.removeEventListener(type, () => cb(), false);
+};
+
+/**
  * 判断url
  * @param url
  */

+ 3 - 0
src/plugins/install.ts

@@ -1,6 +1,8 @@
 import { App } from "vue";
 import { Button, ConfigProvider, Layout, Menu, Modal } from "ant-design-vue";
+
 import VueClipboard3 from "./vue-clipboard";
+import VueConfirmDirective from "./vue-confirm";
 
 import { ModalConfirmKey } from "./injectionKey";
 
@@ -10,6 +12,7 @@ const install = (app: App<Element>) => {
 
   return app
     .use(VueClipboard3)
+    .use(VueConfirmDirective)
     .use(ConfigProvider)
     .use(Layout)
     .use(Menu)

+ 37 - 0
src/plugins/vue-confirm.ts

@@ -0,0 +1,37 @@
+import { App, DirectiveBinding, VNode, createVNode } from "vue";
+import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
+import { Modal } from "ant-design-vue";
+
+import { listener, removeListener } from "@/helper";
+
+const confirmEvent = (binding: DirectiveBinding) => {
+  Modal.confirm({
+    title: "请确认您的操作",
+    content: "确定删除该内容吗?",
+    icon: createVNode(ExclamationCircleOutlined),
+    onOk: () => binding.value.call(),
+  });
+};
+
+const bind = (
+  el: HTMLElement | Element,
+  binding: DirectiveBinding,
+  vnode: VNode
+) => {
+  listener(el, () => confirmEvent(binding));
+};
+
+const unbind = (el: HTMLElement, binding: DirectiveBinding) => {
+  removeListener(el, () => confirmEvent(binding));
+};
+
+const VueConfirmDirective = {
+  install: (app: App<Element>) => {
+    app.directive("confirm", {
+      beforeMount: bind,
+      unmounted: unbind,
+    });
+  },
+};
+
+export default VueConfirmDirective;

+ 6 - 0
src/views/Page1.vue

@@ -1,5 +1,6 @@
 <template>
   <div>page 1
+    <p v-confirm="test">test</p>
     <a-button @click="doCopy">复制</a-button>
   </div>
 </template>
@@ -16,8 +17,13 @@ const Page1 = defineComponent({
       clip.$copyText("copy success");
     };
 
+    const test = () => {
+      console.log("call back");
+    };
+
     return {
       doCopy,
+      test,
     };
   },
 });