allow current window to scroll to top before changing to another router location with vue router

Viewed 212

I would like my page to scroll to the top before changing to another tab. I have tried the following code but in vain.

<b-collapse id="nav-collapse" is-nav>
            <b-navbar-nav class = "ml-5">
                <b-nav-item :active= "$route.matched.some(({ name }) => name === 'tab1')"  class = "navitem" @click= "routehome">tab1</b-nav-item>
                <b-nav-item :active= "$route.matched.some(({ name }) => name === 'tab2')"  class = "navitem" @click= "routeproject">tab</b-nav-item>
                <b-nav-item :active= "$route.matched.some(({ name }) => name === 'tab3')"   class = "navitem" @click= "routeexperience">tab3</b-nav-item>
            </b-navbar-nav>
<b-collapse id="nav-collapse" is-nav>

in script i tried adding this but it doesnt show the animation as the code is running asynchronously.

   totab1() {
        window.scrollTo(0, 0);
        this.$router.push("/tab1");
    },
    totab2() {
        window.scrollTo(0, 0);
        this.$router.push("/tab2");
    },

I then tried adding then function but it seems like windows.scroll(0,0) doesnt support then. Is there a way to work around this?

    totab3() {
        window.scrollTo(0, 0).then(() => {
            this.$router.push("/tab3");
        })
    }
1 Answers

Scroll to Top Before Page Change

This can be achieved with Vue-router's Navigation Guards. Although intended to guard routes, they can just as easily be used to call an arbitrary function before a route change.

You could either call this from within a specific component (using an in component guard) with

beforeRouteLeave() { window.scrollTo(0, 0) }

Or, to apply to all routes, apply in you're router.js file, e.g.

const router = new VueRouter({ ... })

router.beforeEach((to, from, next) => {
  window.scrollTo(0, 0);
})

Scroll to Top After Page Change

Vue router has a useful scrollBehavior method. In you're case you'd want to return { x: 0, y: 0 } to go to the top and left of the page. So in you're router.js file, add something like this:

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