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
}
}
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, 2022Comments
-
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. about 5 yearsJust detect the click outside with a directive and iterate through the open divs and set their display/hide property to false.
-
Learner about 5 yearsdoes not work for me even tho it works in fiddle I get
Cannot set property 'event' of undefined
-
Steven B. about 5 yearsDid you look at the specific answer I linked? not the selected answer of the question as that was for vue 1.x.
-
Learner about 5 years@StevenB. yes i did
-