Prevent event bubbling in Vue

只愿长相守 提交于 2019-11-30 16:26:34

问题


<div id="largeArea" v-on:click="do_X">
    <button>Button</button>
</div>

So I have this issue in Vue where I don't want "do_X" to trigger when I click on the button, although its a part of the largeArea.


回答1:


From the documentation, use the self event modifier to only capture events originating on the element itself...

<div id="largeArea" v-on:click.self="do_X">

new Vue({
  el: '#app',
  methods: {
    do_X () {
      console.log(Date.now(), 'do_X')
    }
  }
})
#largeArea {
  padding: 20px;
  border: 1px solid black;
}
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.js"></script>
<div id="app">
  <div id="largeArea" @click.self="do_X">
    <button>Button</button>
  </div>
</div>



回答2:


I found that using the 'stop' event modifier on the child element worked for me. eg

<div id="app">
  <div id="largeArea" @click="do_X">
    <button @click.stop="do_Y">Button</button>
  </div>
</div>


来源:https://stackoverflow.com/questions/48798216/prevent-event-bubbling-in-vue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!