【问题标题】:Make navigation item active when route doesn't match当路线不匹配时使导航项处于活动状态
【发布时间】:2014-10-10 19:09:34
【问题描述】:

我注意到在使用 EmberJS 时,如果您所在的路由与页面上具有相同路径的链接匹配,它会自动采用“活动”类。

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

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

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

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

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

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

观点/论坛/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');
  });
});

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

【问题讨论】:

  • 你能添加你的路由器代码吗?如果它们正确嵌套,导航将获得活动类
  • 我用路由器编辑了问题。
  • 历史与存档有何关系,服务和消息在哪里?
  • 这些只是我需要的示例。服务和消息与论坛处于同一水平。历史与档案有关,因为我希望它是。
  • 嵌套路由是一种选择吗?

标签: javascript ember.js


【解决方案1】:

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

从 ember 1.8 开始,current-when 可以接受以空格分隔的路由字符串。如需在 1.7 中运行的实现,请查看 Is there a way to pass an array to currentWhen in EmberJS?

【讨论】:

  • 确实如此,但您可以添加一些 CSS 规则,以您想要的方式显示链接(即活动显示为非活动,其他所有内容显示为活动)
  • 要将活动项作为非活动项,这不是真正的 css 语义,更多的是“技巧”
  • 不确定是什么问题。你试过 {{#link-to 'services' current-when='messages'}}Services{{/link-to}} 和 {{#link-to 'forums.archives' current-when='forums.history '}}档案{{/link-to}} ?
【解决方案2】:

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

(假设您的导航栏模板位于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 的计算结果为真,这会将active 类添加到&lt;li&gt;

【讨论】:

  • 这种方法的问题是,当您拥有一个拥有数百个页面的网站时,为您需要定义的所有页面拥有计算属性就会开始变得混乱。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-23
  • 1970-01-01
  • 2021-06-06
  • 1970-01-01
相关资源
最近更新 更多