当前位置: 首页 > 文档资料 > EmberJS 入门教程 >

从具有yield的组件返回值(Return values from a component with yield)

优质
小牛编辑
117浏览
2023-12-01

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

语法 (Syntax)

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

例子 (Example)

下面给出的示例指定具有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}}

输出 (Output)

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

Ember.js组件返回值与收益率

当您单击该链接时,它将显示数组中的对象列表,如下面的屏幕截图所示 -

Ember.js组件返回值与收益率