Search code examples
javascriptnode.jsvue.jsevent-bubblingevent-propagation

Prevent event bubbling in Vue


<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.


Solution

  • 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/[email protected]/dist/vue.js"></script>
    <div id="app">
      <div id="largeArea" @click.self="do_X">
        <button>Button</button>
      </div>
    </div>