Hello hello, I know it's a very annoying issue to find your page reloads after submitting a form or clicking a link that triggers a Vue event handler.
To be on the same page I added this dummy code to increment a number by clicking an anchor tag.
<div id="app">
<a href="#" @click="handleIncrement">Click to increment</a><template> You clicked me: {{count}}</template>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
let app = new Vue({
el:'#app',
data:{
count:1
},
methods:{
handleIncrement(){
this.count++
}
}
})
</script>
Notice the anchor tag reference is equals to a '#' hashtag, If you removed this hashtag you will break the flow and nothing will happen when you click the same link.
But leaving this hashtag causes the issue I'm talking about, you'll find the page reloads after every and each single click. This issue is known as the default behavior.
Because Vue is a very smart JS framework the solution is very handy. You'll add ".prevent" to the event handler so it will be like "@click.prevent" this will prevent the default behavior after clicking the link.
Check the following code updates
- ADD: ".prevent" to the event handler (@click ->@click.prevent)
- UPD: the anchor-tag and nullified the reference (href="#" -> href='')
<a href="" @click.prevent="handleIncrement">Click to increment</a><template> You clicked me: {{count}}</template>
Now your page will work like a champion and never reloads again.
Top comments (0)