Vue-router: Un-register Navigation Guard

Created on 8 Apr 2017  路  3Comments  路  Source: vuejs/vue-router

What problem does this feature solve?

I have a navigation guard that needs to run upon first load, do some stuff, and then never be called again. The check to see if the guard should be activated is a slow IPC call. It would be nice to unregister the guard when it is no longer needed, just like you would remove an event listener.

This is not a huge issue - I can get around it by storing the results of the expensive call in a vuex store. But it would be cleaner to remove when not needed.

What does the proposed API look like?

function guard(to, from, next) {
...
}

router.beforeEach(guard)
...
router.removeBeforeEach(guard)
feature request

Most helpful comment

Implemented in 7731488 - beforeEach will return a function that will remove the registered fn.

All 3 comments

in the meantime you can do what I do:

function guard(to, from, next) {
 // ...
}

guard.hookName = 'guard';

router.beforeHooks.forEach((hook, index, hooks) => {
  if (hook.hookName === 'guard') {
    hooks.splice(index, 1);
  }
});

Implemented in 7731488 - beforeEach will return a function that will remove the registered fn.

Well, does this solution mean:

// register
formerhook = router.beforeEach(fn)
//unregister
formerhook() 

to remove the former hook?

reference
https://github.com/vuejs/vue-router/issues/1106#issuecomment-374456405

Was this page helpful?
0 / 5 - 0 ratings