SoFunction
Updated on 2025-04-13

Vue @How to prevent events from being passed to ancestor elements (events bubbling)

I've encountered this problem recently:

There is a parent div containing a child div. It is required to execute the fun() function when clicking the parent div, and not to execute the fun() function when clicking the child div.

You can use @ to prevent events from passing to parent elements

1. @Introduction

In Vue, @click is a directive that listens for click events of an element. @ is one of the modifiers, which is used to prevent events from bubbled, that is, prevent events from being passed to parent elements.

Specifically, when an element is clicked, all parent elements in the DOM hierarchy it is located receive the event. If a similar @click event is also bound to the parent element, the event will also be triggered. When an element using the @ modifier is clicked, the event will no longer be passed to the parent element. This prevents events from being triggered multiple times unnecessarily.

2. No event triggers

<template>
  <div @click="fun">
    <div @>
      <!--sondiv-->
    </div>
  </div>
</template>

<script>
export default {
  methods: {
    fun() {
      // Functions executed when clicking on the parent div      ('Clicked the parent div');
    },
  },
}
</script>

3. Do not trigger parent event, trigger your own event

<template>
  <div @click="doSomething">
    <button @="doSomethingElse">The click event of the parent element will not be triggered</button>
  </div>
</template>
<script>
export default {
  methods: {
    doSomething() {
      ('doSomething')
    },
    doSomethingElse() {
      ('doSomethingElse')
    }
  }
}
</script>

In the example above, when the button is clicked, only the doSomethingElse method is triggered, and the doSomething method is not triggered.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.