每一个组件都是相对独立的,所以任何组件所需的数据都须要经过组件的属性把数据传递到组件中。php
好比上篇《Ember.js 入门指南——组件定义》的第三点“{{component item.pn post=item}}”就是经过属性post把数据传递到组件foo-component或者bar-component上。若是在index.hbs中是以下方式调用组件那么渲染以后的页面是空的。html
{{component item.pn}}
请读者本身修改index.hbs的代码后演示效果。json
传递到组件的参数也是动态更新的,当传递到组件上的参数变化时组件渲染的HTML也会随之发生改变。数组
传递的属性参数不必定要指定参数的名字。你能够不指定属性参数的名称,而后根据参数的位置获取对应的值,可是要在组件对应的组件类中指定位置参数的名称。好比下面的代码:app
准备工做:post
ember g route passing-properties-to-componentthis
ember g component passing-properties-to-componentspa
调用组件的模板,传入两个位置参数,分别是item.title、item.body。code
<!-- app/templates/passing-properties-to-component.hbs --> {{#each model as |item|}} <!-- 传递到组件blog-post第一个参数为数据的title值,第二个为body值 --> {{passing-properties-to-component item.title item.body}} {{/each}}
准备须要显示的数据。component
// app/routes/padding-properties-to-component.js import Ember from 'ember'; export default Ember.Route.extend({ model: function() { return [ { id: 1, title: 'Bower: dependencies and resolutions new', body: "In the bower.json file, I see 2 keys dependencies and resolutionsWhy is that so? " }, { id: 2, title: 'Highly Nested JSON Payload - hasMany error', body: "Welcome to the Ember.js discussion forum. We're running on the open source, Ember.js-powered Discourse forum software. " }, { id: 3, title: 'Passing a jwt to my REST adapter new ', body: "This sets up a binding between the category query param in the URL, and the category property on controller:articles. " } ]; } });
在组件类中指定位置参数的名称。
// app/components/padding-properties-to-component.js import Ember from 'ember'; export default Ember.Component.extend({ // 指定位置参数的名称 positionalParams: ['title', 'body'] });
注意:属性positionalParams指定的参数不能在运行期改变。
组件直接使用组件类中指定的位置参数名称获取数据。
<!-- app/templates/components/passing-properties-to-component.hbs --> <article> <h1>{{title}}</h1> <p>{{body}}</p> </article>
注意:获取数据的名称必需要与组件类指定的名称一致,不然没法正确获取数据。
显示结果以下:
Ember还容许你指定任意多个参数,可是组件类获取参数的方式就须要作点小修改。好比下面的例子:
调用组件的模板
<!-- app/templates/passing-properties-to-component.hbs --> {{#each model as |item|}} <!-- 传递到组件blog-post第一个参数为数据的title值,第二个为body值 --> {{passing-properties-to-component item.title item.body 'third value' 'fourth value'}} {{/each}}
指定参数名称的组件类,获取参数的方式能够参考计算属性这章。
// app/components/padding-properties-to-component.js import Ember from 'ember'; export default Ember.Component.extend({ // 指定位置参数为参数数组 positionalParams: 'params', title: Ember.computed('params.[]', function() { return this.get('params')[0]; //获取第一个参数 }), body: Ember.computed('params.[]', function() { return this.get('params')[1]; //获取第二个参数 }), third: Ember.computed('params.[]', function() { return this.get('params')[2]; //获取第三个参数 }), fourth: Ember.computed('params.[]', function() { return this.get('params')[3]; //获取第四个参数 }) });
下面看组件是怎么获取传递过来的参数的。
<!-- app/templates/components/passing-properties-to-component.hbs --> <article> <h1>{{title}}</h1> <p>{{body}}</p> <p>third: {{third}}</p> <p>fourth: {{fourth}}</p> </article>
显示结果以下:
到此组件参数传递的内容所有介绍完毕。总的来讲没啥难度。Ember中参数的传递与获取方式基本是类似的,好比link-to助手、action助手。