DEV Community

Ibrahim
Ibrahim

Posted on

How to Handle Click Outside Events in Vue 3

The click outside event is commonly used in components like modal, dropdown, and so on.

For example, in a modal component, when a user clicks outside the modal, the event is triggered and the modal is closed.

By default, Vue 3 doesn't provide a handler for this event. However, you can use the vue3-click-outside package as a solution.

To start handling click outside events in Vue 3, first install the vue3-click-outside package:

npm install --save click-outside-vue3
# or
yarn add click-outside-vue3
Enter fullscreen mode Exit fullscreen mode

Next, open your main Vue setup file (usually in main.js). Import the package and use it on the Vue instance.

import { createApp } from "vue"
import App from "./App.vue"
import vClickOutside from "click-outside-vue3"

const app = createApp(App)
app.use(vClickOutside)
Enter fullscreen mode Exit fullscreen mode

After that, we can start handling click outside events on an element by adding v-click-outside directive. For example:

<!-- BaseModal.vue -->
<script setup>
import { ref } from 'vue'

const visible = ref(false)

const onClickOutside = () => visible.value = false
</script>

<template>
    <div class="modal-wrapper" v-if="visible">
        <div class="modal-content" v-click-outside="onClickOutside">
            <!-- Modal Content -->
        </div>
    </div>
</template>
Enter fullscreen mode Exit fullscreen mode

Here's the result:

Handling click outside event

Now, when a user clicks outside the modal, the event will be triggered and the modal will close.

Top comments (1)

Collapse
 
devops_fundamental profile image
DevOps Fundamental

Very interesting this content