vueuse 中文文档

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
Catalog
vueuse 入门 State 状态 Elements 元素 Browser 浏览器 Sensors 感应监测 onClickOutside 侦听元素外部点击 onKeyStroke 监听按键 onLongPress 长按事件 onStartTyping 非编辑元素输入时触发 useBattery 获取电池状态。 useDeviceMotion 设备方向及运动信息 useDeviceOrientation 方向变化信息 useDevicePixelRatio 屏幕像素比 useDevicesList 可用设备列表