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
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)
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>
Here's the result:
Now, when a user clicks outside the modal, the event will be triggered and the modal will close.
Top comments (1)
Very interesting this content