Vue.js scroll to top of page for same route

You can't do this trough vue-router. But you can add scroll to top method to every router-link.

Just create a method

methods: { 
  scrollToTop() {
    window.scrollTo(0,0);
  }
}

And add it to the link

<router-link @click.native="$scrollToTop">

If you wanna use it outside of your footer too it's better to add it to the Vue prototype

Vue.prototype.$scrollToTop = () => window.scrollTo(0,0)

It's not a 100% solution but it's the simplest one


I wanted to answer this question to add more to people coming to this question where scroll behaviour isn't working at all.

I couldn't get any of the above solutions working, and it was really frustrating.

What ended up working for me was the below:

const router = new Router({
    mode: 'history',
    routes: [...],
    scrollBehavior() {
        document.getElementById('app').scrollIntoView({ behavior: 'smooth' });
    }
})

I mount my VueJs app to #app so i can be certain it is present and is available for selection.


You either can make use of behavior: smooth if you want.

moveTo () {
  let to = this.moveToDown
    ? this.$refs.description.offsetTop - 60
    : 0

  window.scroll({
    top: to,
    left: 0,
    behavior: 'smooth'
  })

  this.moveToDown = !this.moveToDown
}

The best solution I've found for this is: https://router.vuejs.org/guide/advanced/scroll-behavior.html

Specifically:

const router = new VueRouter({
  routes: [...],
  scrollBehavior (to, from, savedPosition) {
    return { x: 0, y: 0 }
  }
})