how to hide dropdown menu if we click outside the menu in vuejs

前端 未结 3 2023
小鲜肉
小鲜肉 2021-01-12 01:08

I am using a dropdown menu components in vuejs to make normal dropdown menu. My code is for dropdown component is :



        
相关标签:
3条回答
  • 2021-01-12 01:15

    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>
    
    0 讨论(0)
  • 2021-01-12 01:22

    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.

    0 讨论(0)
  • 2021-01-12 01:41

    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.

    0 讨论(0)
提交回复
热议问题