DEV Community

Cover image for Vue events causing your page to reload, Here is a quick fix
Mina Farag
Mina Farag

Posted on

1

Vue events causing your page to reload, Here is a quick fix

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Now your page will work like a champion and never reloads again.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay