之前,我的路线是这样定义的:
this.route('username', {
path: '/:username'
}, function() {
this.route("room", {
path: "/:room",
});
我把它改成:
this.route('username', {
path: '/:username'
}, function() {
this.route('index')
});
this.route("room", {
path: "/:room"
});
这很好用。但是我的 username/index
路由不会加载,除非我在 router.js
中明确定义索引。
以下将不工作:
this.route('username', {
path: '/:username'
});
this.route("room", {
path: "/:room",
});
这是正常行为吗?
最佳答案
当一个route
有嵌套的route
时,假定父级有一个index
路由。这在指南中指的是:https://guides.emberjs.com/v2.13.0/routing/defining-your-routes/#toc_index-routes
特别是关键短语是:
At every level of nesting (including the top level), Ember automatically provides a route for the / path named index. To see when a new level of nesting occurs, check the router, whenever you see a function, that's a new level.
因此,在您的示例中,因为 room
嵌套在 username
中,所以 username
会自动获得一个 index
路线。当您从嵌套中删除 room
时,username
的默认 index
路由就消失了。
仅供引用,您甚至不必指定索引路由,只需提供一个空回调即可。例如:
this.route('username', {
path: '/:username'
}, function() {});
这将通过自动创建 username/index
路由以相同的方式工作。
在我早期的一个 Ember 应用程序 (1.x) 中,我希望索引路由始终存在(为了保持一致性),所以我定义了一个变量:
var NO_CHILDREN= function() {};
然后我可以这样写我的路线:
this.route('username', {
path: '/:username'
}, NO_CHILDREN);
希望对你有帮助
关于javascript - 为什么我需要在 Ember.js 中定义一个索引路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43941336/