DEV Community

Cover image for Using vue-clickaway for your dropdowns
Ayoazeez26
Ayoazeez26

Posted on

Using vue-clickaway for your dropdowns

Do you ever want to close a dropdown anytime the user clicks outside of it? vue-clickaway is a package that covers listening for clicks outside an element so you can perform actions when it happens. I will be taking you on the easy installation process and how to use it within your components.

PREREQUISITE

Click here to install the package via npm or yarn. After installing, the recommended way of usage is to import clickaway into the component you intend to use it as a mixin like this:

import { mixin as clickaway } from 'vue-clickaway';

The next step is to call the mixin inside your

export default like this mixins: [ clickaway ]

After that, you call the method you want to trigger on clickaway in your template on your dropdown parent element.

v-on-clickaway="away"

Final step is to create the away function and watch the magic happen. Let's go ahead to demonstrate an example for you so you can understand how it works, if you don't already.

This example was built on a Nuxt.js project. The first thing I did after installing clickaway was to create it as a plugin so I would not have to import it and use it as a mixin on every component I intend to use it on

// plugins/clickaway.js

import { mixin as clickaway } from 'vue-clickaway'
import Vue from 'vue'

Vue.mixin({
  mixins: [clickaway]
})

Enter fullscreen mode Exit fullscreen mode

Now add the clickaway file inside the plugins array in your nuxt.config.js

// nuxt.config.js

plugins: [ '~/plugins/clickaway' ],

Enter fullscreen mode Exit fullscreen mode

Now we can go ahead to call our method on the clickaway directive

// components/Navbar.vue
<script>
  export default {
    data: () => ({
      showCityDrop: true,
      cityDrop: [ 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ]
    }),
    methods: {
      closeCityDrop () {
        this.showCityDrop = false;
      }
    }
  }
</script>

<template>
  <div v-if="showCityDrop" v-on-clickaway="closeCityDrop">
    <p v-for="item in cityDrop" :key="index" :to="item.to" class="drop flex items-start text-primary mb-4">
      {{ item }}
    </p>
  </div>
</template>

Enter fullscreen mode Exit fullscreen mode

And that's all you need to do to use clickaway to close your dropdown when the user clicks outside of it. It has other use cases aside the use case demonstrated above. You can use vue clickaway whenever you need to listen outside of an element to perform actions.

I hope you find this helpful

Top comments (0)