【问题标题】:Meteor: Using an HTML Template to add to the DOM.Meteor:使用 HTML 模板添加到 DOM。
【发布时间】:2015-07-10 01:57:21
【问题描述】:

我正在使用 Meteor.js 构建应用程序,并且我有一个表单,我希望能够允许用户在单击按钮时向表单添加新行 (button.addExperience) .我正在使用 HTML 模板来填充表单的每一行。

每次用户单击按钮时如何呈现模板 (experienceRow)?

参见下面的示例代码:

<body>
  <form>       
   {{> experienceRow }}
  </form>
  <button class="addExperience">Add Experience</button>
</body>

<template name="experienceRow">
  <div id={{experienceNumber}} class='experienceRow'>
    <input type="text" placeholder="name" value="" class="name">
    <input type="text" placeholder="address" value="" class="address">
    <input type="text" placeholder="phone" value="" class="phone">
  </div>        
</template>

【问题讨论】:

    标签: meteor


    【解决方案1】:

    您需要使用 each 块和反应变量。该变量可以是ReactiveVar、会话变量、本地集合等。下面是使用ReactiveVar 保存id 数组的示例实现:

    html

    <body>
      {{> experienceForm }}
    </body>
    
    <template name="experienceForm">
      <form>
        {{#each experienceIds}}
          {{> experienceRow }}
        {{/each}}
      </form>
      <button class="addExperience">Add Experience</button>
    </template>
    
    <template name="experienceRow">
      <div id={{this}} class='experienceRow'>
        <input type="text" placeholder="name" value="" class="name">
        <input type="text" placeholder="address" value="" class="address">
        <input type="text" placeholder="phone" value="" class="phone">
      </div>
    </template>
    

    js

    Template.experienceForm.onCreated(function() {
      this.experienceIds = new ReactiveVar(Random.id());
    });
    
    Template.experienceForm.helpers({
      experienceIds: function() {
        return Template.instance().experienceIds.get();
      }
    });
    
    Template.experienceForm.events({
      'click .addExperience': function(e, template) {
        e.preventDefault();
        var ids = template.experienceIds.get();
        ids.push(Random.id());
        template.experienceIds.set(ids);
      }
    });
    

    请注意,您需要meteor add reactive-var 才能使用此功能。

    推荐阅读:scoped reactivity.

    【讨论】:

    • 如果您想跨会话和用户保留每行中的值,那么您需要将它们插入到 集合 而不是反应变量中。
    猜你喜欢
    • 2014-08-10
    • 1970-01-01
    • 2013-10-28
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-28
    • 1970-01-01
    相关资源
    最近更新 更多