onClickOutside
监听元素外部的点击事件。适用于模态框或下拉菜单。
演示
用法
vue
<script setup>
import { onClickOutside } from '@vueuse/core'
import { ref } from 'vue'
const target = ref(null)
onClickOutside(target, event => console.log(event))
</script>
<template>
<div ref="target">
Hello world
</div>
<div>Outside element</div>
</template>
此函数使用 Event.composedPath(),该函数在 IE 11、Edge 18 及更低版本中不受支持。如果您要针对这些浏览器,我们建议您在项目中包含 此代码片段。
组件用法
此函数还通过
@vueuse/components
包提供无渲染组件版本。 了解有关用法的更多信息。
vue
<template>
<OnClickOutside :options="{ ignore: [/* ... */] }" @trigger="count++">
<div>
Click Outside of Me
</div>
</OnClickOutside>
</template>
指令用法
此函数还通过
@vueuse/components
包提供指令版本。 了解有关用法的更多信息。
vue
<script setup lang="ts">
import { vOnClickOutside } from '@vueuse/components'
import { ref } from 'vue'
const modal = ref(false)
function closeModal() {
modal.value = false
}
</script>
<template>
<button @click="modal = true">
Open Modal
</button>
<div v-if="modal" v-on-click-outside="closeModal">
Hello World
</div>
</template>
您还可以将处理程序设置为数组,以设置指令的配置项。
vue
<script setup>
import { vOnClickOutside } from '@vueuse/components'
import { ref } from 'vue'
const modal = ref(false)
const ignoreElRef = ref()
const onClickOutsideHandler = [
(ev) => {
console.log(ev)
modal.value = false
},
{ ignore: [ignoreElRef] },
]
</script>
<template>
<button @click="modal = true">
Open Modal
</button>
<div ref="ignoreElRef">
click outside ignore element
</div>
<div v-if="modal" v-on-click-outside="onClickOutsideHandler">
Hello World
</div>
</template>
类型声明
显示类型声明
typescript
export interface OnClickOutsideOptions extends ConfigurableWindow {
/**
* List of elements that should not trigger the event.
*/
ignore?: MaybeRefOrGetter<(MaybeElementRef | string)[]>
/**
* Use capturing phase for internal event listener.
* @default true
*/
capture?: boolean
/**
* Run handler function if focus moves to an iframe.
* @default false
*/
detectIframe?: boolean
}
export type OnClickOutsideHandler<
T extends {
detectIframe: OnClickOutsideOptions["detectIframe"]
} = {
detectIframe: false
},
> = (
evt: T["detectIframe"] extends true
? PointerEvent | FocusEvent
: PointerEvent,
) => void
/**
* Listen for clicks outside of an element.
*
* @see https://vueuse.org.cn/onClickOutside
* @param target
* @param handler
* @param options
*/
export declare function onClickOutside<T extends OnClickOutsideOptions>(
target: MaybeElementRef,
handler: OnClickOutsideHandler<{
detectIframe: T["detectIframe"]
}>,
options?: T,
): () => void
来源
贡献者
Anthony Fu
sibbng
Anthony Fu
wheat
Onion-L
Matej Černý
不见月
Doctorwu
Rory King
糠帅傅
Chestnut
vaakian X
Fiad
Young
Gavin
webfansplz
Jelf
JserWang
Alex Kozack