DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Salvador GarcΓ­a
Salvador GarcΓ­a

Posted on

Vue 3 Tip / Detect outside click

You need three things for this

NOTE: Options Api gist here

1- A compontent ref like this:


<template>
  <div
    ref="componentRef"
    class="general-style"
  >
  </div>
</template>

<script setup>
import { ref } from 'vue'

const componentRef = ref()
</script>
Enter fullscreen mode Exit fullscreen mode

2- The next composable:

import {onBeforeUnmount, onMounted} from 'vue'

export default function useDetectOutsideClick(component, callback) {
    if (!component) return
    const listener = (event) => {
        if (event.target !== component.value && event.composedPath().includes(component.value)) {
            return
        }
        if (typeof callback === 'function') {
            callback()
        }
    }
    onMounted(() => { window.addEventListener('click', listener) })
    onBeforeUnmount(() => {window.removeEventListener('click', listener)})

    return {listener}
}
Enter fullscreen mode Exit fullscreen mode

3- Use within your component and send the ref as composable param:


<template>
  <div
    ref="componentRef"
    class="general-style"
  >
  </div>
</template>

<script setup>
import { ref } from 'vue'
import useDetectOutsideClick from '/useDetectOutsideClick'

const componentRef = ref()
const exampleComposableText = ref('hello')

useDetectOutsideClick(componentRef, () => { 
exampleComposableText.value = 'edit hello'
})
</script>
Enter fullscreen mode Exit fullscreen mode

Summary: Just declare a ref, point the ref to the template element and send it to the composable as first parameter. The second parameter of the composable is the callback what do you want to execute when clicked out.

Happy Code!

Top comments (0)

🌚 Turn on dark mode

πŸ”  Change your default font

πŸ“š Adjust your experience level to see more relevant content

Head to your account's Settings to do all this and more.