How can I make my vue router go to top of view?

Viewed 676

I have the following problem: When I click on a new component link the router-view will not scroll to 0,0, but it will keep the scrolling state of the old component. It's supposed to move to the top but it doesn't...

https://re-solute.eu/

This is my router in vue

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { x: 0, y: 0 }
    }
  }
})

Thanks for your help!

2 Answers

try to modify the scrollBehavior

// scrollBehavior:
// - only available in html5 history mode
// - defaults to no scroll behavior
// - return false to prevent scroll
const scrollBehavior = (to, from, savedPosition) => {
 if (savedPosition) {
  // savedPosition is only available for popstate navigations.
  return savedPosition
 } else {
  const position = {}
  // new navigation.
  // scroll to anchor by returning the selector
  if (to.hash) {
   position.selector = to.hash
  }
  // check if any matched route config has meta that requires scrolling to top
  if (to.matched.some(m => m.meta.scrollToTop)) {
   // cords will be used if no selector is provided,
   // or if the selector didn't match any element.
   position.x = 0
   position.y = 0
  }
  // if the returned position is falsy or an empty object,
  // will retain current scroll position.
  return position
 }
}

You can also use routing meta information to control scrolling more finely

routes: [
 { path: '/', component: Home, meta: { scrollToTop: true }},
 { path: '/foo', component: Foo },
 { path: '/bar', component: Bar, meta: { scrollToTop: true }}
]

or you can reset the scroll bar to the top when switching routes

  watch: {
    '$route': function(to,from){
     document.body.scrollTop = 0
    }
  }

I had same issue and It worked for me with the below workarounds.

Try 1st this:

scrollBehavior() {
        document.getElementById('app').scrollIntoView();
    }

If still same issue try this:

App.vue



<transition @before-enter="scrollTop" mode="out-in" appear>
  <router-view></router-view>
</transition>



methods: {
  scrollTop(){
   document.getElementById('app').scrollIntoView();
  },
}
Related