perf(dropdown): 新增 useClickOutside 监听, 外部点击关闭 dropdown

This commit is contained in:
就眠仪式 2021-10-16 23:58:19 +08:00
parent 87168bbb00
commit 5468ead4e4
2 changed files with 43 additions and 1 deletions

View File

@ -2,6 +2,7 @@
<div
v-if="trigger === 'click'"
class="layui-dropdown"
ref="dropdownRef"
:class="[openState ? 'layui-dropdown-up' : '']"
>
<div @click="open">
@ -30,7 +31,10 @@
</template>
<script setup name="LaySelect" lang="ts">
import { defineProps, ref } from 'vue'
import { defineProps, ref, watch } from 'vue'
import useClickOutside from '../use/useClickOutside'
const dropdownRef = ref<null | HTMLElement>(null)
const props = withDefaults(
defineProps<{
@ -46,4 +50,13 @@ const openState = ref(false)
const open = function () {
openState.value = !openState.value
}
//
const isClickOutside = useClickOutside(dropdownRef)
// watch
watch(isClickOutside, () => {
if (isClickOutside.value) {
openState.value = false
}
})
</script>

View File

@ -0,0 +1,29 @@
import { ref, onMounted, onUnmounted, Ref } from 'vue'
const useClickOutside = (elementRef: Ref<HTMLElement | null>) => {
// 设置一个导出值
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;