ember组件的动态参数

时间:2016-06-09 15:21:01

标签: javascript ember.js handlebars.js

我正在开发一个Ember项目,我必须动态指定组件的参数。

我在.js控制器中有以下数组:

componentParams: ["id", "name"]

我想要做的是获取数组中的值并在把手中使用它们作为组件参数,如下所示

{{component-name id=somevalue name="somevalue"}}

可以这样做吗?

2 个答案:

答案 0 :(得分:1)

我使用的方法。

controller.js

navbarParams: {
   titleToShow: 'General.ResearchProjects',
   glyphicon: 'glyphicon glyphicon-globe',
   infoText: 'information/project'
},

template.hbs

{{my-navbar params=navbarParams}}

MY-navbar.hbs

<h1> {{params.titleToShow}} <span class={{params.glyphicon}}> </span> </h1>

如果您的参数是queryParams

应该像那样定义

queryParams: ['foo', 'bar',],
foo: null,
bar: null

{{my-navbar first=foo second=bar}}

答案 1 :(得分:1)

老实说,这取决于你是否坚持使用该数组 - 你可以使用计算属性来提取正确的数组值。 (这可能不推荐 - 更好的方法是将componentParams格式化为对象(如@ kristjan的例子)。

如果你坚持使用数组 - 并且位置永远不会改变(id永远是componentParams[0]&amp; name将永远是componentParams[1],你可以尝试这样的东西::

// controller
import Ember from 'ember';

const {
  Controller,
  computed,
  get
} = Ember;

export default Controller.extend({
  componentParams: ['id', 'name'],
    componentName: computed('componentParams', {
    get() {
        return get(this, 'componentParams')[1];
    }
  }),
  componentId: computed('componentParams', {
    get() {
        return get(this, 'componentParams')[0]; 
    }
  })
});


// template
{{my-component name=componentName id=componentId}}

// component/template
name:: {{name}}
<br>
id :: {{id}}

check out this twiddle for a working example

这有帮助吗?

相关问题