目录

将属性传递给组件(Passing Properties to a Component)

组件不直接在模板范围中访问属性。 因此,只需在组件减速时声明属性(例如:{{component-name title = title}})。 外部模板范围中的title属性在组件的模板中可用。

语法 (Syntax)

{{post-action title=title}}

在上面的代码中,'post-action'组件具有'title'属性,并使用与属性名称('title')相同的名称进行初始化。

例子 (Example)

下面给出的示例描述了如何将属性传递给组件。创建名称为post-action的路由并打开router.js文件以定义URL映射 -

import Ember from 'ember';                   
//Access to Ember.js library as variable Ember
import config from './config/environment';
//It provides access to app's configuration data as variable config 
//The const declares read only variable
const Router = Ember.Router.extend ({
   location: config.locationType,
   rootURL: config.rootURL
});
Router.map(function() {
   this.route('post-action');
});
//It specifies Router variable available to other parts of the app
export default Router;  

现在使用以下代码打开组件模板文件post-action.hbs -

<p>Enter your data: {{input type = "text" value = title}}</p>
<p>The details of the object passed are : {{title}}</p>
{{yield}}

打开index.hbs文件并添加以下代码 -

{{post-action title=title}}
{{outlet}}

使用以下代码打开在app/routes/下创建的文件post-action.js文件 -

import Ember from 'ember';
export default Ember.Route.extend ({
   model: function() {
      //assigning the default value for 'title' property
      return {
         title: ""
      };
   }
});

输出 (Output)

运行ember服务器; 你会收到以下输出 -

Ember.js组件传递属性
↑回到顶部↑
WIKI教程 @2018