【问题标题】:How to display multiple routes in one page using Ember js?如何使用 Ember js 在一个页面中显示多个路由?
【发布时间】:2018-04-26 10:58:21
【问题描述】:

我是 Ember 新手,遇到了一个无法解决的问题。我有两条路线 - home 和 lhstree。当 /home 被调用时,我需要渲染两个路由,即。 lhstree 应该在主模板中呈现。为此,我使用了命名outlet。那工作得很好。 但问题是,我需要向 lhstree 模板提供数据。但是永远不会调用 lhstree 模板的模型挂钩。我什至尝试在模型挂钩中添加警报消息,但这也从未执行过。以下是我的代码。任何帮助表示赞赏。

router.js:

Router.map(function() {
 this.route('home');
 this.route('lhstree');
});

home.hbs:

<html>
<head>
</head>
<body>
    Home hbs rendering
    {{outlet 'lhstree'}}
</body>
</html>

home.js:

export default Route.extend({
    renderTemplate:function()
    {
        this.render();
        this.render('lhstree',{outlet:'lhstree',into:'home'});
    }
});

lhstree.hbs:

<ul>
  {{#each model as |player|}}
    <li>{{player}}</li>
  {{/each}}
</ul>

lhstree.js:

model() //THIS MODEL IS NEVER CALLED
{
  return ['Player1', 'Player2'];
}

正如我所提到的,lhstree 路由的模型钩子永远不会被调用。因此,在渲染主页模板时,玩家名称 Player1 和 Player2 永远不会显示。

【问题讨论】:

    标签: javascript html ember.js


    【解决方案1】:

    有两种不同的方法来解决这个问题:

    1. 如果 lhstree 总是出现在主页上,请不要为其使用路由。您可以将其构建为组件,并从父级向下传递属性(因此在 Home 模型路由中获取 lhstree 所需的数据)。所以你的出口将被替换为:

      {{lhstree-component model=model.lhsStuff}}
      
    2. 使 lhstree 成为 Home 的子路由。这样当有人去 home/lhstree 时,Ember 会将 lhstree 模板渲染到 Home 模板内的插座中,并调用这两个模型。为此,请设置您的路线,例如:

      Router.map(function() {
        this.route('home', function() {
          this.route('lhstree');
        });
      });
      

    【讨论】:

    • 嗨,摩根,感谢您的回答。我尝试了您的第二个解决方案,它奏效了。当我访问 home/lhstree 时,两个模板都会被渲染。但问题是,当用户访问 /home 时,我需要同时呈现 home 和 lhstree 模板。有什么建议吗?
    • 我不知道这是否是最佳做法,但我会通过使 lhstree 成为一个组件来解决这个问题。然后你可以在 Home 模板中使用它并传递它需要的东西。如果您还想要一个 lhstree 路由,请制作一个该路由使用的 lhstree 模板,并在该模板中也使用 lhstree 组件
    【解决方案2】:

    虽然rendering a template 您只能将模板设置为outlet,而不是路由。因此,在您的情况下,调用 lhstree.hbs 但不会调用 lhstree.js 路由。如果您想将数据传递给您的插座中的模板,您可以调用 set the data in your home route。你可以看看这个twiddle

    【讨论】:

    • 嘿,Ahmet,您的解决方案有效。但是,如果我必须将数据同时传递给 home 和 lhstree 模板怎么办?
    • @GiridharanJ 我已根据您的评论更新了旋转。现在 home 路由模型为 home 和 lhstree 模板提供数据。
    猜你喜欢
    • 1970-01-01
    • 2022-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多