以 yield 返回组件值



可以使用 yield 选项从组件返回值。

语法

{#each myval as |myval1|}}
   {{ yield myval1 }}
{{/each}}

示例

以下提供的示例指定如何使用 yield 属性从组件返回值。创建一个名为 comp-yield 的路由,并打开 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
});

//Defines URL mappings that takes parameter as an object to create the routes
Router.map(function() {
   this.route('comp-yield');
});

export default Router;

创建 application.hbs 文件,并添加以下代码 −

//link-to is a handlebar helper used for creating links
{{#link-to 'comp-yield'}}Click Here{{/link-to}}
{{outlet}} //It is a general helper, where content from other pages 
   will appear inside this section

打开在 app/routes/ 下创建的 comp-yield.js 文件,并输入以下代码 −

import Ember from 'ember';

export default Ember.Route.extend ({
   model: function() {
      //an array called 'country' contains objects
      return { country: ['India', 'England', 'Australia'] }; 
   }
});

创建一个名为 comp-yield 的组件,并打开在 app/templates/ 下创建的组件模板文件 comp-yield.hbs,其中包含以下代码 −

{{#comp-yield country=model.country as |myval|}}
   <h3>{{ myval }}</h3>
{{/comp-yield}}
{{outlet}}

打开在 app/templates/components/ 下创建的 comp-yield.hbs 文件,并输入以下代码 −

<h2>List of countries are:</h2>
//template iterates an array named 'country'
{{#each country as |myval|}}   //each item in an array provided as blobk param 'myval'
   {{ yield myval }}
{{/each}}

输出

运行 Ember 服务器;你将收到以下输出 −

Ember.js Component Return Values with Yield

当你点击链接时,它将显示一个数组中对象列表,如下面的屏幕截图所示 −

Ember.js Component Return Values with Yield
emberjs_component.htm
广告