路由的变更
Rendering an updated UI when a user reaches a new route is not that useful without giving the user some way to reach a new route! The simplest way is with the trusty <a>
tag and a URL. You can generate the URLs yourself using FlowRouter.pathFor
, but it is more convenient to use the arillo:flow-router-helpers
package that defines some helpers for you:
meteor add arillo:flow-router-helpers
Now that you have this package, you can use helpers in your templates to display a link to a certain route. For example, in the Todos example app, our nav links look like:
<a href="{{pathFor 'Lists.show' _id=list._id}}" title="{{list.name}}"
class="list-todo {{activeListClass list}}">
Routing programmatically
In some cases you want to change routes based on user action outside of them clicking on a link. For instance, in the example app, when a user creates a new list, we want to route them to the list they just created. We do this by calling FlowRouter.go()
once we know the id of the new list:
import { insert } from '../../api/lists/methods.js';
Template.App_body.events({
'click .js-new-list'() {
const listId = insert.call();
FlowRouter.go('Lists.show', { _id: listId });
}
});
You can also change only part of the URL if you want to, using the FlowRouter.setParams()
and FlowRouter.setQueryParams()
. For instance, if we were viewing one list and wanted to go to another, we could write:
FlowRouter.setParams({_id: newList._id});
Of course, calling FlowRouter.go()
, will always work, so unless you are trying to optimize for a specific situation it's better to use that.
Storing data in the URL
As we discussed in the introduction, the URL is really just a serialization of some part of the client-side state the user is looking at. Although parameters can only be strings, it's possible to convert any type of data to a string by serializing it.
In general if you want to store arbitrary serializable data in a URL param, you can use EJSON.stringify()
to turn it into a string. You'll need to URL-encode the string using encodeURIComponent
to remove any characters that have meaning in a URL:
FlowRouter.setQueryParams({data: encodeURIComponent(EJSON.stringify(data))});
You can then get the data back out of Flow Router using EJSON.parse()
. Note that Flow Router does the URL decoding for you automatically:
```js const data = EJSON.parse(FlowRouter.getQueryParam('data'));