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

支持块和非块组件使用(Supporting both block and non-block component usage)

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

您可以使用hasBlock属性支持单个组件中块和非块组件的使用。

语法 (Syntax)

{{#if hasBlock}}
   //code here
{{/if}}

例子 (Example)

下面给出的示例指定在一个模板中支持块和非块组件使用。 创建名为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 () {
      return {
         title: "Emberjs",
         author: "xnip",
         body: "This is introduction"
      };
   }
});

使用名称comp-yield创建一个组件,并使用以下代码打开在app/templates/下创建的组件模板文件comp-yield.hbs -

{{#comp-yield title = title}}
   <p class = "author">by (blocked name){{author}}</p>
   {{body}}
{{/comp-yield}}
{{comp-yield title = title}}
{{outlet}}

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

{{#if hasBlock}}
   <div class = "body">{{yield}}</div>
   {{else}}
   <div class = "body">xnip data is missing</div>
{{/if}}
{{yield}}

输出 (Output)

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

Ember.js组件块和非块组件用法

当您单击该链接时,它将阻止名称,如下面的屏幕截图所示 -

Ember.js组件块和非块组件用法