Scroll behaviour VueJS not working properly Scroll behaviour VueJS not working properly vue.js vue.js

Scroll behaviour VueJS not working properly


Use {left: 0, top: 0} instead of {x: 0, y: 0} and it will work.

I think it's a mistake in Vue documentation because if you log savedPosition on the console, you'll see {left: 0, top: 0} and when you change {x: 0, y: 0} like that everything will work perfectly.


I couldn't get any of the other solutions around this 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();    }})

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


I'm sharing my 2 cents on this problem for anyone like me looking for a working solution. Picking up on Sweet Chilly Philly, answer which was the only thing that worked for me, I'm adding the relevant code to make the URL hash work aswell:

  scrollBehavior: (to, from, savedPosition) => {    if (to.hash) {      Vue.nextTick(() => {        document.getElementById(to.hash.substring(1)).scrollIntoView();      })      //Does not work but it's the vue way      return {selector: to.hash}    }    if (savedPosition) {      //Did not test this but maybe it also does not work      return savedPosition    }    document.getElementById('app').scrollIntoView();    //Does not work but it's the vue way    return {x: 0, y: 0}  }

I won't get into much detail about Vue.nextTick (you can read more about it here) but it kinda runs the code after the next DOM update, when the route already changed and the element referenced by the hash is already ready and can be reached through document.getElementById().