【问题标题】:Dynamically generate components based on array of objects基于对象数组动态生成组件
【发布时间】:2017-10-19 19:58:57
【问题描述】:

好吧,我对 Ember(以及类似的框架)还很陌生,所以如果我遗漏了一些明显的东西,请原谅我。

我有一个包含一些逻辑的设置菜单组件。该逻辑的一部分是一个计算属性,它返回一个对象数组(可能的设置)。它将数据向下传递到视图组件。

menu-component.js

possibleSettings: computed(function() {
    // Example of returned data
    return [
        {
            type: 'time',
            min: 1,
            max: 60,
        },
        },
            type: 'sound',
            values: [‘alarm’, ‘beep’, ‘rooster’],
        },
    ]
});

menu-component.hbs

{{menu-component/menu-view
    possibleSettings=possibleSettings}}

每个设置都有自己的组件,例如:

menu-component/time.hbs

<label>Time</label>
{{input value=time}}

menu-component/sound.hbs

<label>Sound</label>
{{dropdown items=sounds}}

我希望视图组件根据可能设置的结果来呈现这些组件。所以按照上面的示例数据,它需要同时渲染 Time 和 Sound 组件。

我想我需要这样的东西,但我无法理解最后一点。我可以用全新的眼光看待事物。

menu-component/settings-view.hbs

<div>
    {{#each possibleSettings as |setting|}}
        {{#if (eq setting.type time)}}
            {{component ‘menu-component/time'}}
        {{else if (eq setting.type sound)}}
            {{component ‘menu-component/sound'}}
        {{/if}}
    {{/each}}
</div>

非常感谢任何帮助。

【问题讨论】:

    标签: ember.js handlebars.js


    【解决方案1】:

    问题似乎在于您没有在车把中将time 括在引号中,因此它在组件本身上寻找名为time 的属性,而不是字符串"time"。另外,我认为您不需要在这里使用组件助手,因为无论如何您都在硬编码组件名称。这是您在这方面编辑的hbs

    <div>
      {{#each possibleSettings as |setting|}}
        {{#if (eq setting.type "time")}}
          {{menu-component/time}}
        {{else if (eq setting.type "sound")}}
          {{menu-component/sound}}
        {{/if}}
      {{/each}}
    </div>
    

    或者,你可以这样做:

    {{#each possibleSettings as |setting|}}
      {{component (concat 'menu-component/' setting.type)}}
    {{/each}}
    

    【讨论】:

    • 我完全忘记了 concat,这就是我试图实现的解决方案。同时,我的计算属性名称中有一个错字,这就是为什么我花了两个小时试图弄清楚为什么我无法访问 object.keys .... d'oh!干杯。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 2017-07-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-20
    • 1970-01-01
    相关资源
    最近更新 更多