How to stop mouse event propagation in Vue.js

in Code Write a comment

In this tutorial, you’ll learn how to easily stop mouse event propagation (DOM bubbling) in Vue.js.

When you have a Vue.js method called from href tag you’ll experience DOM bubbling. It is a default browser behaviour. When you click on the <a> tag browser will navigate to the href.

Consider this example:

new Vue({
  el: "#app",
  data: { },
  methods: {
  	toggle: function(){
    	console.log('clicked')
    }
  }
})
<div id="app">
  <a href="#" @click="toggle()">Click</a>
</div>

If you scroll down and click the link it will scroll the page up and bubble the DOM.


Hi, I'm Renat 👋

 


Use .prevent or event.preventDefault()

To prevent the default browser behaviour you can use .prevent or event.preventDefault().

<div id="app">
  <a href="#" @click.prevent="toggle()">Click</a>
</div>

If you find this post useful, please let me know in the comments below. 
Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/vue-js-mouse-propagation

PS: Make sure you check other Vue.js tutorials, e.g. radio button binding in Vue.js and useful Vue.js filters.

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment

Comment