Meteor Blaze:在渲染父模板之前不要等待子模板渲染

Meteor Blaze : dont wait for child template rendering before rendering parent

在玩 Blaze 时我意识到以下几点: 如果我有一个父模板,其中包含一个带有 {{> child_template }}

的子模板

然后 Blaze 将在渲染父模板之前等待子模板被渲染。这在某些情况下可能很好,但不是全部。

例如,如果我的父模板包含 <h1>Welcome to my page</h1> 和子模板包含 10 000 个项目的列表。我想要一种尽快显示 <h1> 并等待 10 000 项稍后出现的方法

我目前正在做的事情如下:

Template.parent.onRendered(function(){
    Blaze.render(Template.child, document.body);
});

它正在工作,但我想知道是否有人有更好的解决方案来解决这个看起来很常见的问题。谢谢

如您所说,您的 Child 模板有一个包含 10000 个项目的列表。所以,这意味着您已经订阅了一些 collection。您可以使用下面的代码来解决您的问题。

<template name="Parent">
    <div>
        <h1>Welcome to my page</h1>
    </div>
  {{#if Template.subscriptionsReady}}
    {{> Child}}
  {{else}}
  <p>Loading Child Items...</p>
  {{/if}}
</template>

您可以将自定义布尔参数传递给默认为 false 的子组件,但父组件的 onRendered 将其设置为 true。并且子组件应该检查​​这个参数并且不渲染任何东西,除非它是 true.

Template.parent.onCreated(function() {
  this.state = new ReactiveDict();
  this.state.setDefault({
    "canRender": false,
  });
}

Template.parent.onRendered(function() {
  this.state.set("canRender", true);
}

Template.parent.helpers({
  canRender() {
    return Template.instance().state.get("canRender");
  }
});

将状态传递给子组件:

<template name="parent">
  {{>child canRender=canRender}}
</template>

<template name="child">
  {{#if canRender}}
    <p>Millions of items go here.</p>
  {{/if}}
</template>