Prevent event bubbling in Vue

前端 未结 4 767
轮回少年
轮回少年 2020-12-09 14:35

So I have this issue in Vue where I don\'t wa

相关标签:
4条回答
  • 2020-12-09 15:22

    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>
    
    0 讨论(0)
  • 2020-12-09 15:27

    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>

    0 讨论(0)
  • 2020-12-09 15:30

    Prevent bubbling for all clicks inside a container <div>

    <div @click.stop="" class="action">
    
      <button @click="someClickAction1()">Action 1</button>
    
      <button @click="someClickAction2()">Action 2</button>
    
    <div>
    

    Prevent bubbling on an existing click action

    <button @click.stop="someClickAction()">Single Action</button>
    
    0 讨论(0)
  • 2020-12-09 15:37

    Neither of the provided answers. In my situation it's wrapped in a <router-link> not a <div>.

    I called e.preventDefault() on the child element and it worked

    <router-link>
        <div @click="do_X"></div>
    </router-link>
    
    new Vue({
      el: '#app',
      methods: {
        do_X (e) {
        e.preventDefault();
          console.log(Date.now(), 'do_X')
        }
      }
    })
    
    0 讨论(0)
提交回复
热议问题