EmberJS 將屬性傳遞到組件

2018-01-03 13:58 更新

將屬性傳遞到組件

組件不直接在模板范圍中訪問(wèn)屬性。要解決這個(gè)問(wèn)題,只需在組件減速時(shí)聲明屬性({{my-comp title=title}})。這只是,組件模板中可用的外部模板范圍中的title屬性與title屬性的名稱相同。

<script type="text/x-handlebars">
   //component name
   {{my-comp title=title}}
</script>

<script type="text/x-handlebars" data-template-name="components/my-comp">
   // This is component
</script>

在上面的代碼中,'my-comp'組件具有'title'屬性,并且使用與屬性名('title')相同的名稱初始化。

例子

<!DOCTYPE html>
<html>
   <head>
      <title>Emberjs Passing Properties to a Component</title>
      <!-- CDN's-->
      <script src="/attachements/w3c/handlebars.min.js"></script>
      <script src="/attachements/w3c/jquery-2.1.3.min.js"></script>
      <script src="/attachements/w3c/ember.min.js"></script>
      <script src="/attachements/w3c/ember-template-compiler.js"></script>
      <script src="/attachements/w3c/ember.debug.js"></script>
      <script src="/attachements/w3c/ember-data.js"></script>
   </head>
   <body>
      <script type="text/x-handlebars" data-template-name="index">
         <!-- passing title property to a component -->
         {{my-name title=title}}
      </script>

      <script type="text/x-handlebars" data-template-name="components/my-name">
         <!-- this is the 'my-name' component -->
         <p><b>The details of the object passed are</b> :{{title}}</p>
         <p><b>Enter your data:</b>{{input type="text" value=title}}</p>
      </script>

      <script type="text/javascript">
         App = Ember.Application.create();

         App.IndexRoute = Ember.Route.extend({
            model: function() {
               //assigning the default value for 'title' property
               return {
                  title: "Tutorialspoint"
               };
            }
         });
      </script>
   </body>
</html>

輸出

讓我們執(zhí)行以下步驟,看看上面的代碼如何工作:

  • 將上述代碼保存在 comp_passng_prprt.html 文件中

  • 在瀏覽器中打開此HTML文件。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)