K
K
kroha30002019-10-19 16:38:19
Vue.js
kroha3000, 2019-10-19 16:38:19

How to hide a block when clicking on any area?

There is a div. Opened by clicking on the link. Basic example.
Click here: (click to open, click to close)
<a @click="isActive = !isActive">Ссылка</a>
Open this div:
<div :class="{active: isActive}"></div>

data() {
     isActive : false
  }

Question: How can I make it close when clicking on any area of ​​the screen, except for the div itself. That is, not to a link, but to any area. And just closing.
Opened Div by link - close div by clicking anywhere.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-10-19
@kroha3000

data: () => ({
  active: false,
}),
created() {
  const onClick = e => this.active = this.$refs.block.contains(e.target) && this.active;
  document.addEventListener('click', onClick);
  this.$on('hook:beforeDestroy', () => document.removeEventListener('click', onClick));
},

<button @click.stop="active = !active">click me</button>
<div :class="{ active }" ref="block">hello, world!!</div>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question