我有一个如下的Ember组件类;
import Ember from 'ember';
import myappconstants from '../utils/constants';
export default Ember.Component.extend({
constants: myappconstants.FIELD_CONSTANTS.SECTION_1,
myConfigs: {
[myappconstants.FIELD_CONSTANTS.SECTION_1.FIELD_1] : {fieldName:"my__label__1", type:"text"},
[myappconstants.FIELD_CONSTANTS.SECTION_1.FIELD_2] : {fieldName:"my__label__2", type:"text"}
}
})
我的问题在我的组件类中,我想以略有不同的方式定义“ myConfigs”键。这是因为定义最多可以增加到20个左右,将来任何名称更改都必须在多个地方进行。
所以我希望将其定义为
myConfigs: {
[this.constants.FIELD_1] : {fieldName:"my__label__1", type:"text"},
[this.constants.FIELD_2] : {fieldName:"my__label__2", type:"text"}
}
使用上面的代码,我得到一个错误; 无法读取未定义的属性“常量”
是否可以实现上述命名?
答案 0 :(得分:1)
如果要使myConfigs
与constants
属性相关,可以使用computed property
答案 1 :(得分:1)
您可以使用与组件类一起获得的willRender
钩子,并使用.set()
来设置myConfigs
属性。
它看起来像这样:
import Ember from 'ember';
import myappconstants from '../utils/constants';
export default Ember.Component.extend({
willRender() {
const sec1Constants = myappconstants.FIELD_CONSTANTS.SECTION_1;
this.set('myConfigs', {
`${sec1Constants.FIELD_1}`: {fieldName:"my__label__1", type:"text"},
`${sec1Constants.FIELD_2}`: {fieldName:"my__label__2", type:"text"}
});
}
});
注意:如果您选择在.set()
上进行任何类型的myConfigs
,则要使用Ember Object代替POJO作为设置对象。