Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set afterEach handler in vue-router

I have the following script:

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

export default new Router({
  scrollBehavior (to, from, savedPosition) {
    // purposely left blank
  },
  routes: [
    {
      path: "/",
      component: SampleComponent
    }
  ]
}

I would like to add an afterEach handler to the router so that I can close any open menus when a router link is taken.

I tried to add it to the constructor but it is not a constructor argument.

I also tried:

Router.afterEach((to, from) => {
  // ...
})

But I get an error:

afterEach is not a function

How do I appropriately add an afterEach callback with this setup?

like image 491
Christopher Avatar asked Oct 19 '25 21:10

Christopher


1 Answers

You need to set the afterEach handler on a Router instance (the object returned via new Router()).

You can set a reference to your instance, and add the afterEach handler to it before it's exported:

const router = new Router({
  scrollBehavior (to, from, savedPosition) {
    // purposely left blank
  },
  routes: [
    {
      path: "/",
      component: SampleComponent
    }
  ]
});

router.afterEach((to, from) => {
  // ...
});

export default router
like image 116
thanksd Avatar answered Oct 21 '25 11:10

thanksd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!