Navigating
After configuring your routes, you need to enable navigation by starting your router instance.

Starting your router

1
const myRouter = createRouter([
2
{ name: 'home', path: '/home' },
3
{ name: 'about', path: '/about' },
4
{ name: 'contact', path: '/contact' }
5
]);
6
7
myRouter.start('/home');
Copied!
When using .start(), you should supply a starting path or state except if you use the browser plugin (the current URL will automatically be used).
Invoking the .start(startPathOrState[, done]) function will:
  • Attempt to navigate to startPathOrState
  • Attempt to match the current URL if no startPathOrState was provided, or navigation failed
  • Attempt to navigate to the default route if it could not match the provided start path or if startPathOrState was not provided / failed
And will:
  • Enable navigation
Providing a starting state is designed to be used for universal JavaScript applications: see universal applications.

Defining a default route

A default route can be set in createRouter options. The following example will cause your application to navigate to /about:
1
var myRouter = createRouter([
2
{ name: 'home', path: '/home' },
3
{ name: 'section', path: '/:section' }
4
], {
5
defaultRoute: 'section'
6
defaultParams: {section: 'about'}
7
})
8
.start(function (err, state) {
9
/* ... */
10
});
Copied!
A callback can be passed to start and will be invoked once the router has transitioned to the default route.

Navigating to a specific route

Router5 exposes the following method: navigate(routeName, routeParams, opts). This method has to be called for navigating to a different route: clicks on links won't be intercepted by the router.
1
myRouter.navigate('section', {section: 'contact'});
2
// Will navigate to '/contact'
Copied!

Forcing a reload

When trying to navigate to the current route nothing will happen unless reload is set to true.
1
myRouter.navigate('section', {section: 'contact'}, {reload: true});
Copied!

Replacing current state

Set replace to true for replacing the current state in history when navigating to a new route. Default behaviour is to add an entry in history.
1
myRouter.navigate('section', {section: 'contact'}, {replace: true});
Copied!

Custom options

You can pass any option to navigate: those options will be added to the state of your router (under meta).
Like for .start(), .navigate() accepts a callback (last argument):
1
myRouter.navigate('route', function (err, state) {
2
/* ... */
3
})
Copied!

Stopping your router

At any time you can stop (pause) a router and it will prevent any navigation. To resume, simply invoke .start() again.
1
myRouter.stop();
Copied!
Last modified 3yr ago