下面是我的组件的代码,我也在使用VueUse,我想在槽元素之外点击时触发vueUse的“onClickOutside”功能。
但无法获得与 Nuxt 2 不同的完美元素,它不起作用!
<template>
<div class="flex flex-col items-center justify-center min-h-screen fixed inset-0 p-5 bg-gray-300/75 z-50">
<slot />
</div>
</template>
<script>
export default {
mounted() {
onClickOutside(this.$slots.default()[0], (event) => {
this.$emit('close')
})
}
}
</script>
将
onClickOutside()
绑定在包装器上而不是插槽上,因为 this.$slots.default()[0]
可能是 null
<template>
<div
ref="wrapper"
class="flex flex-col items-center justify-center min-h-screen fixed inset-0 p-5 bg-gray-300/75 z-50">
<slot />
</div>
</template>
<script lang="ts" setup>
import { onClickOutside } from '@vueuse/core';
const emits = defineEmits([
'close'
]);
let clickoutsideObserver: ReturnType<typeof onClickOutside> | undefined;
const wrapper: Ref<null|HTMLDivElement> = ref(null);
clickoutsideObserver = onClickOutside(
wrapper,
() => {
emits('close');
}
);
// destroy the observer to save the memory
onBeforeMount(() => {
clickoutsideObserver? clickoutsideObserver() : null;
});
</script>