onClickOutside
onClickOutside
要素の外側でのクリックを監視します。モーダルやドロップダウンに便利です。
使用方法
<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 オプションを使用できます。
const { cancel, trigger } = onClickOutside(
modalRef,
(event) => {
modal.value = false
},
{ controls: true },
)
useEventListener('pointermove', (e) => {
cancel()
// または
trigger(e)
})
特定の要素を無視したい場合は、ignore オプションを使用できます。無視する要素を Refs または CSS セレクタの配列として指定します。
const ignoreElRef = useTemplateRef<HTMLElement>('ignoreEl')
const ignoreElSelector = '.ignore-el'
onClickOutside(
target,
event => console.log(event),
{ ignore: [ignoreElRef, ignoreElSelector] },
)
コンポーネントの使用
<template>
<OnClickOutside :options="{ ignore: [/* ... */] }" @trigger="count++">
<div>
Click Outside of Me
</div>
</OnClickOutside>
</template>
ディレクティブの使用
<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-outside="closeModal">
Hello World
</div>
</template>
ハンドラを配列として設定し、指示の設定項目を指定することもできます。
<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-outside="onClickOutsideHandler">
Hello World
</div>
</template>
© 2019–PRESENT Anthony Fu https://github.com/antfu
※このページは Nuxt.js 公式ドキュメントの翻訳ページです。
公式ドキュメントの該当ページはこちら:
#