Ember.js如果未提供,则显示默认嵌套路由



在我的余烬应用程序(1.0.0生产版本)中,我有一个URL结构,如下所示:

/item
/item/{specific-item-name-defined-in-routes}

路由器映射看起来有点像这样:

App.Router.map(function () {
    this.resource("item", function () { 
        this.resource("my-first-item");
        this.resource("another-item");
        ...
    });
});

如果用户导航到/item我想显示一个特定的帖子(例如 /item/my-first-item )。 我可以使用路由的redirect方法来做到这一点:

App.ItemRoute = Ember.Route.extend({
    redirect: function () {
        this.transitionTo('my-first-item');
    }
});

不幸的是,如果我手动在地址栏中输入 URL /item/another-item或直接导航到应用程序/item/another-item将我重定向到/item/my-first-item,则使用这种方法。 如果我只是在嵌套路由之间切换(即通过单击应用程序中的链接,它会正确加载)。

如何让重定向仅在未提供嵌套路由时才起作用?

不要重定向项目路由,而是将重定向挂钩添加到(自动生成的)ItemIndexRoute:

App.ItemIndexRoute = Ember.Route.extend({
  redirect: function () {
    this.transitionTo('my-first-item');
  }
});

Ember-cli 和 pods 结构的更新

Mike Grassotti 的回答仍然是正确的,但我还想添加一个更新,说明在使用新的 pods 应用程序结构时,如何在 Ember 2.x 中使用 ember-cli 实现这一点。使用 pod 时,您需要在所需 pod 内创建一个 index 文件夹,然后您可以在该索引文件夹中放置一个route.js文件,以便解析器可以找到它。

示例目录/文件结构

 pods
  ├─ application
  │   ├─ route.js
  │   ├─ controller.js
  │   └─ template.hbs
  └─ item
      ├─ index
      │    └─ route.js
      ├─ my-first-item
      │    ├─ route.js
      │    ├─ controller.js
      │    └─ template.hbs
      └── another-item
           ├─ route.js
           ├─ controller.js
           └─ template.hbs

示例路由.js

上面的pods/item/index/route.js文件如下所示:

import Ember from 'ember';
var ItemIndexRoute = Ember.Route.extend({
  redirect: function() {
    this.transitionTo('my-first-item');
  }
});
export default ItemIndexRoute;

仅供参考,根据 Ember 2.6 的官方文档

像这样的嵌套路由器:

app/router.js

Router.map(function() {
  this.route('posts', function() {
    this.route('favorites');
  });
});

相当于:

app/router.js

Router.map(function(){
  this.route('index', { path: '/' });
  this.route('posts', function() {
    this.route('index', { path: '/' });
    this.route('favorites');
  });
});

最新更新