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.
function guard(to, from, next) {
...
}
router.beforeEach(guard)
...
router.removeBeforeEach(guard)
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
Most helpful comment
Implemented in 7731488 -
beforeEachwill return a function that will remove the registered fn.