onClickOutside
Listen for clicks outside of an element. Useful for modal or dropdown.
Demo
Usage
<template>
<div ref="target">
Hello world
</div>
<div>
Outside element
</div>
</template>
<script>
import { ref } from 'vue'
import { onClickOutside } from '@vueuse/core'
export default {
setup() {
const target = ref(null)
onClickOutside(target, (event) => console.log(event))
return { target }
}
}
</script>
<template>
<div ref="target">
Hello world
</div>
<div>
Outside element
</div>
</template>
<script>
import { ref } from 'vue'
import { onClickOutside } from '@vueuse/core'
export default {
setup() {
const target = ref(null)
onClickOutside(target, (event) => console.log(event))
return { target }
}
}
</script>
This function uses Event.composedPath() which is NOT supported by IE 11, Edge 18 and below. If you are targeting these browsers, we recommend you to include this code snippet on your project.
Component
This function also provides a renderless component version via the@vueuse/components
package. Learn more about the usage. <OnClickOutside @trigger="count++">
<div>
Click Outside of Me
</div>
</OnClickOutside>
<OnClickOutside @trigger="count++">
<div>
Click Outside of Me
</div>
</OnClickOutside>
Type Declarations
export interface OnClickOutsideOptions extends ConfigurableWindow {
/**
* List of elements that should not trigger the event.
*/
ignore?: MaybeElementRef[]
}
/**
* Listen for clicks outside of an element.
*
* @see https://vueuse.org/onClickOutside
* @param target
* @param handler
* @param options
*/
export declare function onClickOutside(
target: MaybeElementRef,
handler: (evt: PointerEvent) => void,
options?: OnClickOutsideOptions
): (() => void) | undefined
export interface OnClickOutsideOptions extends ConfigurableWindow {
/**
* List of elements that should not trigger the event.
*/
ignore?: MaybeElementRef[]
}
/**
* Listen for clicks outside of an element.
*
* @see https://vueuse.org/onClickOutside
* @param target
* @param handler
* @param options
*/
export declare function onClickOutside(
target: MaybeElementRef,
handler: (evt: PointerEvent) => void,
options?: OnClickOutsideOptions
): (() => void) | undefined
Source
Contributors
Anthony Fu
Nurettin Kaya
wheat
Jelf
JserWang
Alex Kozack