Do you need to detect a click outside an element with NUXT.JS or Vue.JS?

Graphic art representing a click outside a Vue.JS modal

If we want to improve the experience of our users we should consider to facilitate the closing of elements that could be disruptive. In this article we will show you how to detect clicks outside an element to close it. To achieve this we will use v-click-outside , a Vue directive developed by Nicolas del Valle .

Adding this directive to our project will be able to use a method to hide a DOM element whenever the user clicks out of it.

How to add v-click-outside in your project with Vue CLI:

With Yarn:

yarn add v-click-outside

With NPM:

npm install --save v-click-outside

Add in your main.js file in the src folder:


  import Vue from 'vue';  
  import vClickOutside from 'v-click-outside';  
     
  Vue.use(vClickOutside);        
            

Add v-click-outside in a Nuxt.JS project:

Until now we were not able to find a Nuxt component for v-click-outside but we always can added to our project as a plugin. We will show you how to do it here:

With Yarn:

yarn add v-click-outside

With NPM:

npm install --save v-click-outside

Now you can create a vClickOutside.js file in the plugins folder of your Nuxt project with the following configuration:

import Vue from "vue"
import vClickOutside from "v-click-outside"

Vue.use(vClickOutside)
            

We almost finished. Now we need to register the new plugin vClickOutside.js in our nuxt.config.js file:

/*
** Plugins to load before mounting the App
*/
plugins: [
{ src: "@/plugins/vClickOutside", ssr: false }
],
            

Use of the v-click-outside directive in Vue and Nuxt:

You are ready to use the v-click-outside directive in any element:


<template>
  <div v-click-outside="externalClick">
       Hello, I am the div to hide!
  </div>
</template>
       
<script>
  import vClickOutside from 'v-click-outside'
  export default {
    directives: {
      clickOutside: vClickOutside.directive
    },
    methods: {
      externalClick (event) {
        console.log('External click. Event: ', event)
      }
    }
  };

     </script>

Once the v-click-outside is added to an element you will be ready to detect any click outside of it. The rest is easy, we only need to adapt the associated method to hide the selected element.

Remember, you will need to import vClickOutside in each component that you intend to use it, and also add it as a directive of the component.

You are all set! Your users will appreciated nex time they visit your website.