Skip to content

onClickOutside

监听元素外部的点击。对于模态或下拉菜单很有用。

¥Listen for clicks outside of an element. Useful for modal or dropdown.

示例

用法

¥Usage

vue
<script setup lang="ts">
import { 
onClickOutside
} from '@vueuse/core'
import {
useTemplateRef
} from 'vue'
const
target
=
useTemplateRef
<HTMLElement>('target')
onClickOutside
(
target
,
event
=>
console
.
log
(
event
))
</script> <template> <
div
ref
="
target
">
Hello world </
div
>
<
div
>Outside element</
div
>
</template>

如果你需要更好地控制触发处理程序,可以使用 controls 选项。

¥If you need more control over triggering the handler, you can use the controls option.

ts
const { 
cancel
,
trigger
} = onClickOutside(
modalRef, (
event
) => {
modal.value = false }, {
controls
: true },
) useEventListener('pointermove', (
e
) => {
cancel
()
// or
trigger
(
e
)
})

如果你想忽略某些元素,可以使用 ignore 选项。将要忽略的元素作为 Refs 或 CSS 选择器数组提供。

¥If you want to ignore certain elements, you can use the ignore option. Provide the elements to ignore as an array of Refs or CSS Selectors.

ts
const 
ignoreElRef
=
useTemplateRef
<HTMLElement>('ignoreEl')
const
ignoreElSelector
= '.ignore-el'
onClickOutside( target,
event
=>
console
.
log
(
event
),
{
ignore
: [
ignoreElRef
,
ignoreElSelector
] },
)
js
const ignoreElRef = useTemplateRef('ignoreEl')
const ignoreElSelector = '.ignore-el'
onClickOutside(target, (event) => console.log(event), {
  ignore: [ignoreElRef, ignoreElSelector],
})

组件用法

¥Component Usage

vue
<template>
  <OnClickOutside 
:options
="{
ignore
: [/* ... */] }" @
trigger
="count++">
<
div
>
Click Outside of Me </
div
>
</OnClickOutside> </template>

指令用法

¥Directive Usage

vue
<script setup lang="ts">
import { 
vOnClickOutside
} from '@vueuse/components'
import {
shallowRef
} from 'vue'
const
modal
=
shallowRef
(false)
function
closeModal
() {
modal
.
value
= false
} </script> <template> <
button
@
click
="
modal
= true">
Open Modal </
button
>
<
div
v-if="
modal
"
v-on-click-outs
ide="
closeModal
">
Hello World </
div
>
</template>

还可以将 handler 设置为数组来设置指令的配置项。

¥You can also set the handler as an array to set the configuration items of the instruction.

vue
<script setup lang="ts">
import { 
vOnClickOutside
} from '@vueuse/components'
import {
shallowRef
,
useTemplateRef
} from 'vue'
const
modal
=
shallowRef
(false)
const
ignoreElRef
=
useTemplateRef
<HTMLElement>('ignoreEl')
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-outs
ide="
onClickOutsideHandler
">
Hello World </
div
>
</template>