[Vuejs]-Hide div when clicking the main div, but not when clicking child divs, hrefs, spans etc

2👍

I believe that is what the v-on:click.self modifier does. See here in the docs.

👤LShapz

1👍

As @LShapz answered, the modifier=.self should be the recommended approach (Vue Style).

Another way is compare $event.target === $event.currentTarget (not recommended for your use case, but you may use these two properties for some other situations in future).

Vue.config.productionTip = false
new Vue({
	el: '#app',
  data: {
  	modal: true
  },
  methods: {
  	toggle: function(ev){
    	if(ev.target === ev.currentTarget) this.modal = !this.modal
    }
  }
});
a {
  color: white
}
#content {
  width: 300px;
  height: 300px;
  background: blue;
  color: white;
}
<script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
<div id="app">
  <div v-if="modal" id="content" @click="toggle($event)">
    <h3>
      Name
    </h3>
    <span>
      <a href="">Like this</a>
    </span>
  </div>
  <button @click="toggle">Toggle</button>
</div>
👤Sphinx

Leave a comment