DEV Community

Salvador García
Salvador García

Posted on

5 1

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!

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (3)

Collapse
 
programmer110 profile image
Syed Zaigham Ali Zai

On popup div, i placed a ref, to close it when clicked outside, and there is a button for opening a popup, upon clicking button it treats it the outside element and goes to callback function, where popup close logic is implemented and in result popup never opens, please suggest to ignore button click

Collapse
 
georginklv profile image
georginklv

how to handle it for when i have more then one comp i mean i use it for dropdown how to know which one to close ?

Collapse
 
kirkbushell profile image
Kirk Bushell

Why not write a custom directive?

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay