【问题标题】:Can't iterate over collection and insert into template无法遍历集合并插入模板
【发布时间】:2015-03-31 16:46:19
【问题描述】:

我是 Meteor 的初学者,无法完成简单的任务,即遍历集合并将每个项目的单个属性打印到模​​板。我打开了自动发布,所以我没有编写发布/订阅功能。到目前为止我所做的所有其他组件都可以工作,所以我很确定问题出在下面的代码中。

在 HTML 中(注意注释)

  <template name="tags">
    <div class="tags">
            {{#each printTags }}
                    {{name}} <br>
            {{/each }}
            <!-- why is nothing showing up here? -->
    </div>
  <template>

在JS文件中

    if (Meteor.isClient) {

      Tags = new Mongo.Collection("tags")

      tags = Tags.find({}).fetch();

      Template.tags.helpers({
            printTags: tags
      });
    }

在客户端,在开发工具中

    Tags.find().fetch().forEach(function(tag){console.log(tag["name"])})
    1
    2
    3
    4
    5

【问题讨论】:

    标签: meteor


    【解决方案1】:

    您的代码的问题在于,您的 printTags 助手被分配给一个变量 (tags),该变量保存了集合尚未填充数据时获取集合文档的结果。

    您必须使用函数,以便在数据可用时重新评估表达式:

    Template.tags.helpers({
      printTags: function(){
        return Tags.find();
      }
    });
    

    【讨论】:

    • 这不是反应性的,调用 .fetch() 会停止。为了使用来自 db 的响应式数据,您必须返回 cursor docs.meteor.com/#/full/mongo_cursor
    • 你是对的,在这种情况下返回游标更合适,因为 Blaze 可以优化 #each 以仅重新渲染其部分内容。但是,触发响应性的不是您在响应式计算中返回的内容,而是被评估并最终依赖的响应式数据源,因此即使您使用 fetch 返回一个普通数组,帮助器仍然是响应式的,因为 find 调用会触发响应性.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-03
    • 2016-01-07
    • 2011-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多