I am using a dropdown
menu components in vuejs to make normal dropdown menu.
My code is for dropdown
component is :
I know it's quite an old question but I think the best way to do that without any external plugins is to add a click listener to mounted lifecycle hook (and remove it on beforeDestroy hook) and filter the clicks on your component so it only hides when clicked outside.
<template>
<span class="dropdown" :class="{shown: state}">
<a href="#" @click.prevent="toggleDropdown" class="dropdown-toggle">toggle menu</a>
<div class="dropdown-menu" v-show="state">
<ul class="list-unstyled">
<slot></slot>
</ul>
</div>
<transition/>
</span>
</template>
<script>
export default {
name: 'dropdown',
data () {
return {
state: false
}
},
methods: {
toggleDropdown (e) {
this.state = !this.state
},
close (e) {
if (!this.$el.contains(e.target)) {
this.state = false
}
}
},
mounted () {
document.addEventListener('click', this.close)
},
beforeDestroy () {
document.removeEventListener('click',this.close)
}
}
</script>
You can make use of the blur
event, e.g. if you add a method:
close() {
setTimeout(() => {
this.state = false;
}, 200);
}
And set the blur
event for your link:
<a href="#" @click.prevent="toggleDropdown" @blur="close">toggle menu</a>
Then the dropdown will get hidden whenever your toggle link loses focus.
The setTimeout
is necessary because Javascript click events occur after blur, which would result in your dropdown links being not clickable. To work around this issue, delay the menu hiding a little bit.
Have a look at vue-clickaway.(Link)
Sometimes you need to detect clicks outside of the element (to close a modal window or hide a dropdown select). There is no native event for that, and Vue.js does not cover you either. This is why vue-clickaway exists. Please check out the demo before reading further.