【问题标题】:How to dynamically build navigation menu from routes linking to parent/child views/controllers如何从链接到父/子视图/控制器的路由动态构建导航菜单
【发布时间】:2017-03-16 11:03:30
【问题描述】:

这个问题是我原来的问题Linking directly to both parent+child views/controllers from the main navigation menu的后续问题

接受的答案很好,但后来当我动态添加第二个“childRoute”时,我注意到了一个问题。为了动态构建我的导航,我必须添加具有相同“路线”属性的多条路线。 (请参阅下面示例代码中的 app.js)。唯一的区别是“标题”和“设置”属性。

configureRouter(config, router){
    config.title = 'Aurelia';
    config.map([
        { route: 'shared-parent', moduleId: './shared-parent', settings: { childRoute: 'child-a' }, nav: true, title: 'Shared Parent - child-a' },
        { route: 'shared-parent', moduleId: './shared-parent', settings: { childRoute: 'child-b' }, nav: true, title: 'Shared Parent - child-b' },
        ...
    ]);

    this.router = router;
  }

我在视图中使用的设置属性:

<a if.bind="row.settings.childRoute" href.bind="row.href + '/' + row.settings.childRoute">${row.title}</a>

我知道它不漂亮,但它确实导航到正确的子路线。问题在于,它始终是 2 条路线中的最后一条,具有重复的“路线”属性被标记为活动。

我之所以添加 settings: {childRoute: 'child-a/b' } 而不是给它们像 route: 'shared-parent/child-a'route: 'shared-parent/child-b' 这样的不同“路由”属性,是因为 URL 实际上会匹配 shared-parent/child-a/child-ashared-parent/child-b/child-b,因为我们是第一次链接到共享父级。

这个实时可运行的gist应该清楚地显示问题(子路由永远不会激活):https://gist.run/?id=95469a9cb3a762d79da31e0b64248036

附言。 如果您对如何称呼此问题的标题有更好的了解,请随时对其进行编辑。

【问题讨论】:

    标签: aurelia


    【解决方案1】:

    因此,我在子视图模型的激活生命周期挂钩中使用 EventAggregator 解决了您的问题。

    https://gist.run/?id=bfb5df5e39ac0bb73e9e1cae2d2496e2

    在子视图模型中,我刚刚发布了一个事件,说明子路由已更新:

    activate(params, routeConfig, navigationInstruction) {
      let payload = navigationInstruction.parentInstruction.config.title;
    
      payload = payload.substring(0, payload.length - 7);
    
      this.aggregator.publish("child route updated", payload + "child-a");
    
    }
    

    在 app.js 文件中,我更新了路线标题,并添加了一个 activeChild 属性。接下来,在捕获事件时更新 activeChild 属性:

    constructor(aggregator) { 
    
      this.aggregator = aggregator; 
    
    
    
      this.aggregator.subscribe("child route updated", payload => { 
    
        this.activeChildRoute = payload;
    
        console.log(this.activeChildRoute);
    
      });
    
    }
    

    最后,我更新了列表项上的类表达式,以根据该活动子标志进行更新:

        <li repeat.for="row of router.navigation" 
            class="${row.title === activeChildRoute ? 'active' : ''}">
    

    【讨论】:

    • 嗨詹姆斯。这实际上是一个绝妙的解决方案。我刚刚在每条路由中添加了activationStrategy: 'replace',,以便它不会“保留”子路由之间的父状态。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多