Dependency injection
When using lifecycle methods (canActivate, canDeactivate), middleware or plugins, you might need to access specific objects from your application: a store, a specific API, etc... You can pass their reference to router5 and they will be passed alongside your router instance.
For TypeScript users, createRouter accepts a generic for typing dependencies.
You can register all dependencies at once, or one by one.
1
const router = createRouter(routes, options, dependencies)
Copied!
1
router.setDependencies({ store, api })
2
// or
3
router.setDependency('store', store)
4
router.setDependency('api', api)
Copied!
You can retrieve your current dependencies references using getDependencies().
Lifecycle methods (canActivate, canDeactivate), middleware or plugins will be called with them:
1
const plugin = (router, dependencies) => ({
2
/*
3
onStart() {},
4
onStop() {},
5
onTransitionStart() {},
6
...
7
*/
8
})
Copied!
1
const canActivate = (router, dependencies) =>
2
(toState, fromState, done) {
3
/* ... */
4
}
Copied!
1
const middleware = (router, dependencies) =>
2
(toState, fromState, done) {
3
/* ... */
4
}
Copied!
Last modified 1yr ago
Copy link