【问题标题】:Use different components depending on a property of a model根据模型的属性使用不同的组件
【发布时间】:2015-05-31 12:05:52
【问题描述】:

在我的 Ember 应用中,我创建了一个具有颜色属性的模型

   App.Gecko = DS.Model.extend({
       color: fusia

    })

在模板中,我想根据 Gecko 的颜色运行不同的组件,所以我的模板中所需的逻辑是这样的

 {{#each item in model}}
       {{if item.color == green}}
             code for a component
       {{/if}}
       {{if item.color == blue}}
            code for some other component
       {{/if}}
 {{/each}}

除了 Handlebars 不支持 {{ if item.color == green }} 逻辑。我知道我应该为此使用计算属性,但我不知道如何设置它,以便根据项目的颜色运行不同的组件。问题:如何使用控制器上的计算属性(我假设它属于控制器)根据模型中的属性运行不同的组件?

更新 针对第一个答案,我尝试使用新的(从 1.11 开始)组件助手,遵循提交中显示的模式 https://github.com/lukemelia/ember.js/commit/16b70236e0904cc76335c34fae8ef2c035b0657b 这就是我所说的

{{#each item in model}}
    {{ component renderGeckoComponent model=item }}

{{/each}}

在我的控制器中,我有这个

   renderGeckoComponent: function(){
    var col = this.get('model.color');
     console.log("even though there are many instances, this only runs once and ")
    if (color === "fusia"){
      console.log("going to have a component here")
    }else if (color === "pink"){
      console.log("going to have a component here")
   }
   }.property('model.color')

结果:当我尝试打开属性时,它显示undefined

var col = this.get('model.color');  //col is undefined
console.log(col) //undefined

【问题讨论】:

  • 你有:var col = this.get('model.color'); -- 但是你正在检查if (color === "fusia") { .. 一个是col 一个是color...

标签: ember.js


【解决方案1】:

关于支持val1 == val2,有一个插件:ember-truth-helpers

要使用计算属性动态创建组件,有{{component}} helper

【讨论】:

  • 感谢您的帮助。您介意展示如何使用它,而不是仅仅链接。我尝试遵循提交消息中的模式,但无法访问我需要打开的属性。查看更新和github.com/lukemelia/ember.js/commit/…
猜你喜欢
  • 1970-01-01
  • 2019-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-01
  • 1970-01-01
相关资源
最近更新 更多