VueUse onClickOutside 侦听元素外部的点击

VueUse onClickOutside 指定一个侦听元素,当点击该元素的外部区域事将触发事件,适用于模态或下拉列表。

代码示例

<script setup lang="ts">
import { ref } from 'vue'
import { onClickOutside } from '@vueuse/core'

//监听的元素
const target = ref(null)

onClickOutside(target, (event )=> {
//你点击了该元素的外部区域
console.log(event)
})
</script>
<template>
  <div ref="target">
    Hello world
  </div>
  <div>Outside element</div>
</template>

组件示例

<template>
  <OnClickOutside :options="{ ignore: [/* ... */] }" @trigger="count++">
    <div>
      Click Outside of Me
    </div>
  </OnClickOutside>
</template>
<script setup>  
 //导入组件
 import {OnClickOutside} from '@vueuse/components'
</script>

指令示例

<script setup>
import { ref } from 'vue'
import { vOnClickOutside } from '@vueuse/components'

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>

忽略某元素

<script setup>
import { ref } from 'vue'
import { vOnClickOutside } from '@vueuse/components'

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>

在线例子

例子

类型定义

export interface OnClickOutsideOptions extends ConfigurableWindow {
  /**
   * List of elements that should not trigger the event.
   */
  ignore?: (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