【问题标题】:Meteor show and hide Template on click点击时流星显示和隐藏模板
【发布时间】:2016-02-18 06:42:32
【问题描述】:

我想在单击按钮时显示一个模板而不是另一个模板。类似于 StackOverFlow 问题中的“添加评论”链接。在下面的示例中,我想将 {{> newCommentLink}} 替换为 {{> postEditor}}

<template name="main">
  {{#each posts}}
        {{> posts}}
   {{/each}}
</template>

<template name="posts">
  {{#each comments}}
        {{> comment}}
  {{/each}}
  {{> newCommentLink}}
</template>

如果不行,有没有其他办法?

【问题讨论】:

    标签: meteor iron-router meteor-blaze


    【解决方案1】:

    您可以使用reactive variable 来确定要显示的模板:

    Template.posts.onCreated(function() {
        this.newCommentLink = new ReactiveVar(true);
    });
    
    Template.posts.helpers({
        shouldShowNewCommentLink() {
          return Template.instance().newCommentLink.get();
        }
    });
    
    Template.posts.events({
        'click button': function(event, template) {
          template.newCommentLink.set(!template.newCommentLink.get());
        }
    });
    

    在模板中:

    <template name="posts">
      {{#each comments}}
            {{> comment}}
      {{/each}}
      <button class="btn btn-default">Click me to switch...</button>
      {{#if shouldShowNewCommentLink}}
        {{> newCommentLink}}
      {{else}}
        {{>postEditor}}
      {{/if}}
    </template>
    

    【讨论】:

    • 这不是只创建一个变量吗?并且只有一个事件监听器?有不止一个帖子。对吗?
    • 变量和事件的范围应该只限于当前模板实例,因此每个帖子实例都有一个变量/事件。
    猜你喜欢
    • 1970-01-01
    • 2012-05-06
    • 2018-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多