On click outside of some element in vue without packages

10,374

Vue way is to use this.$el (DOM element of current component), you can change this.$el and use any other HTMLElement

<div class="modal" @click="handleClick">
  <div class="modal-dialog">
    <div class="modal-content">
    ...
    </div>
</div>

And method should look like this

handleClick(e: Event): void {
  if (e.target instanceof HTMLElement && !this.$el.contains(e.target)) {
    this.$emit("hide"); //fires only on click outside
  }
}
Share:
10,374
Learner
Author by

Learner

I am learner and good seeker. I like to eat and hug my bunny. I would like to live forever with everyone else and stop aging after 50 years old. I would also like to expand life everywhere around the space.

Updated on July 30, 2022

Comments

  • Learner
    Learner over 1 year

    I am wondering how can we hide all shown elements on click outside from those elements in vue:

    <button @click="div1=true">Show div 1</button>
    <div v-if="div1">DIV 1</div>
    
    <button @click="div2=true">Show div 2</button>
    <div v-if="div2">DIV 2</div>
    

    How can I hide all divs besides div 1 if I click on div 1 or hide all divs on click on some random part of the page? How does vuetify handle it?

    • Steven B.
      Steven B. about 5 years
      Just detect the click outside with a directive and iterate through the open divs and set their display/hide property to false.
    • Learner
      Learner about 5 years
      does not work for me even tho it works in fiddle I get Cannot set property 'event' of undefined
    • Steven B.
      Steven B. about 5 years
      Did you look at the specific answer I linked? not the selected answer of the question as that was for vue 1.x.
    • Learner
      Learner about 5 years
      @StevenB. yes i did