From 5468ead4e40f5d90622836236dcfe50d7a636f0d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E5=B0=B1=E7=9C=A0=E4=BB=AA=E5=BC=8F?= <854085467@qq.com>
Date: Sat, 16 Oct 2021 23:58:19 +0800
Subject: [PATCH] =?UTF-8?q?perf(dropdown):=20=E6=96=B0=E5=A2=9E=20useClick?=
=?UTF-8?q?Outside=20=E7=9B=91=E5=90=AC,=20=E5=A4=96=E9=83=A8=E7=82=B9?=
=?UTF-8?q?=E5=87=BB=E5=85=B3=E9=97=AD=20dropdown?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
src/module/dropdown/index.vue | 15 ++++++++++++++-
src/module/use/useClickOutside.ts | 29 +++++++++++++++++++++++++++++
2 files changed, 43 insertions(+), 1 deletion(-)
create mode 100644 src/module/use/useClickOutside.ts
diff --git a/src/module/dropdown/index.vue b/src/module/dropdown/index.vue
index 875fb43e..1ddfaa8e 100644
--- a/src/module/dropdown/index.vue
+++ b/src/module/dropdown/index.vue
@@ -2,6 +2,7 @@
@@ -30,7 +31,10 @@
diff --git a/src/module/use/useClickOutside.ts b/src/module/use/useClickOutside.ts
new file mode 100644
index 00000000..2d71e4a5
--- /dev/null
+++ b/src/module/use/useClickOutside.ts
@@ -0,0 +1,29 @@
+import { ref, onMounted, onUnmounted, Ref } from 'vue'
+
+const useClickOutside = (elementRef: Ref) => {
+
+ // 设置一个导出值
+ const isClickOutside = ref(false);
+
+ // 给界面绑定上事件
+ const handler = (e: MouseEvent) => {
+ if (elementRef.value) {
+ // e.target 有可能是为 null 所以需要断言
+ if (elementRef.value.contains(e.target as HTMLElement)) {
+ // 判断目标节点是不是当前的节点
+ isClickOutside.value = false;
+ } else {
+ isClickOutside.value = true
+ }
+ }
+ }
+ onMounted(() => {
+ document.addEventListener('click', handler);
+ });
+ onUnmounted(() => {
+ document.removeEventListener('click', handler);
+ });
+ return isClickOutside;
+}
+
+export default useClickOutside;
\ No newline at end of file