Skip to content

onClickOutside

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

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

示例

用法

¥Usage

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>

组件用法

¥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 { 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>

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

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

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/onClickOutside
 * @param target
 * @param handler
 * @param options
 */
export declare function onClickOutside<T extends OnClickOutsideOptions>(
  target: MaybeElementRef,
  handler: OnClickOutsideHandler<{
    detectIframe: T["detectIframe"]
  }>,
  options?: T,
): () => void

源代码

源代码示例文档

变更日志

v12.4.0 on 1/10/2025
dd316 - feat: use passive event handlers everywhere is possible (#4477)
v12.3.0 on 1/2/2025
59f75 - feat(toValue): deprecate toValue from @vueuse/shared in favor of Vue's native

VueUse 中文网 - 粤ICP备13048890号