组件和它们周围的环境是隔离的,所以组件需要的任何数据都需要传递进去。
例如,想象你有一个blog-post
组件,用来显示博客文章:
{{article class='blog-post'}}
<h1>{{title}}</h1>
<p>{{body}}</p>
{{/article}}
现在想象我们有下面的模板和路由:
//in route index.js
export default Route.extend({
model() {
return this.store.findAll('post');
}
})
如果我们试图使用这种组件:
{{#each model as |post|}}
{{blog-post}}
{{/each}}
下面的HTML将会被渲染:
<article class='blog-post'>
<h1></h1>
<p></p>
</article>
为了使组件的属性可用,你必须像这样将属性传进进去:
{{#each model as |post|}}
{{blog-post title=post.title body=post.body}}
{{/each}}
重要的是要注意这些属性保持同步(技术上成为绑定),也就是说,如果组件中componentProperty
的值改变,outerProperty
将会反映更新变化。反之亦然。
除了使属性可用,还可以为组件提供action
。它允许数据流回到它的父元素。你可以这样传递action
:
{{button-with-confirmation text='click here to use' onConfirm=(action "unsubscribe")}}
需要注意,action只能从controller或其他component传递。他们不能从route传递过来。想了解更多关于传递action的细节,请参阅 passing an action to the component。
定位参数
除了通过名字传递参数,你还可以通过位置传递他们。换句话说,你可以像这样调用上面的组件示例:
{{#each model as |post|}}
{{blog-post post.title post.body}}
{{/each}}
要将组件设置为用这种方式接收参数,你需要在组件类中设置[
positionalParams`](https://www.emberjs.com/api/ember/release/classes/Component/properties/positionalParams?anchor=positionalParams)属性。
//in component.js
export dafault Component.extend({}).reopenClass({
positionalParams: ['title', 'body'],
})
然后你就可以像使用{{blog-post title=post.title body=post.body}}
一样使用组件中的属性。
注意positionalParams
属性通过reopenClass
作为静态变量添加到类中。位置参数始终在组件类上声明,并且在程序运行时无法更改。
另外,你可以通过将positionalParams
设置为字符串来接收任意数量的参数,例如,positionalParams: 'params'
。它允许你将这些参数作为数组访问,像下面这样:
import {computed} from '@ember/object';
export dafult Component.extend({
title: computed('params.[ ]', function() {
return this.params[0];
}),
body: computed('params.[]', function() {
return this.params[1];
})
}).reopenClass({
positonalParams: 'params'
})