当路线没有't匹配

Make navigation item active when route doesn't match

本文关键字:匹配 当路      更新时间:2023-09-26

我注意到,使用EmberJS,如果您所在的路由与页面上具有相同路径的链接匹配,则会自动获取类"active"。

我目前正在构建一个使用此功能的导航栏,但我担心的是,并非所有路线都与导航栏匹配。

例如,当我在路线/messages中时,我想使项目/services处于活动状态。或者,当我在路线/forums/history中时,我想使项目/forums/archives处于活动状态。尽管导航中没有这条路线,但我想突出显示与之相关的项目。

我的导航是从一个json对象生成的,它看起来像:

[
  {
    "label": "Forums",
    "link": "forums",
    "children": [
      {
        "label": "Latest"
        "link": "forums.latest"
      }
      {
        "label": "Archives"
        "link": "forums.archives"
      }
    ]
  }
]

我有几个不喜欢的想法,这就是为什么我来这里听取你的建议。以下是我的想法:

  • 在视图中定义一个属性,以定义哪个项目应在导航中处于活动状态:

views/forums/history.js:

Ember.View.extend({
  navigationActiveItem: 'forums.archives'
});
  • 在我的json对象中定义将突出显示项目的链接列表

json文件:

[
  {
    "label": "Forums",
    "link": "forums",
    "children": [
      {
        "label": "Archives"
        "link": "forums.archives",
        "makeActive": ["forums.history", "forums.records"] //If you are on one of those route, it will active forums.archives
      }
    ]
  }
]

router.js:

Router.map(function () {
  this.route('forums', function () {
    this.route('latest');
    this.route('archives');
    this.route('history');
  });
});

你对做这样的事有什么更好的建议吗?感谢

使用{{#link to}}的current-when参数。它将允许您定义导致链接处于活动状态的替代路线。

自ember 1.8以来,current何时可以接受空格分隔的路由字符串。对于在1.7中工作的实现,请查看EmberJS中是否有方法将数组传递给currentWhen?

我这样做的方法是在应用程序控制器中设置属性。

(这假设您的导航栏模板在application.handlebars中)

例如,如果你希望你的"论坛"选项卡在任何forums路线上都是活动的,你可以创建一个名为isForums的属性,它看起来像这样:

isForums: function(){
  return this.get('currentPath').split('.')[0] === 'forums';
}.property('currentPath')

然后,您可以从application.handlebars访问它,如下所示:

<li {{bind-attr class="isForums:active"}}>
  {{#link-to "forums"}}Forums{{/link-to}}
</li>

如果isForums的计算结果为true,则会将active类添加到<li>中。