如何将参数传递给ember组件

how to pass parameters to ember component

本文关键字:ember 组件 参数传递      更新时间:2023-09-26

此成员组件模板:

<script type="text/x-handlebars" id="components/blog-post">
  <h1>Component: {{title}}</h1>
  <p>Lorem ipsum dolor sit amet.</p>
</script>

这是组件代码:

App.BlogPostComponent = Ember.Component.extend({
    // how can i access the title property here? (this.title doesn't work)
    // also this.get('title') throws error: undefined is not a function
    computedProp: 'width' + this.title
});

它的用途:

{{blog-post title=title body=body}}

我可以使用{{title}}从组件模板轻松访问title属性。

如何从组件代码App.BlogPostComponent中访问title属性。

还有一种简单的方法可以在车把中燃烧属性,例如:

<h1 style="width: {{percent}}%">

编辑

当我按照建议这样做时:

App.BlogPostComponent = Ember.Component.extend({
  computedProp: function () {
    return 'width' + this.get('title');
  }.property('title')
});

我得到错误:

Uncaught Error: Assertion Failed: Attributes must be numbers, 
strings or booleans, not function () {
            return 'width:' + 50 + '%';
        } 

编辑2:好的,错误的原因是在函数定义的末尾省略了.property('title')。现在已经修复了。

this.get应该可以正常工作,问题是您没有在对象上下文中调用它。定义计算属性的正确方法是:

App.BlogPostComponent = Ember.Component.extend({
  computedProp: function () {
    return 'width' + this.get('title');
  }.property('title')
});

<h1 style="width: {{percent}}%">这样的东西现在是不可能的,你应该使用bind-attr助手+计算属性。