没有路由的流星动态内容

Meteor dynamic content without routing

在不创建路由的情况下更改页面内容的最佳做法是什么?

BlazeLayout.render('mainLayout', { top: 'header', menu: 'menu', main: 'dashboard', bottom: 'footer' });

如何在不创建新路由的情况下 hide/show 仪表板内的模板组件?这是否应该在助手中使用 html 中的某种 if/else 逻辑并在按钮单击时使用助手来完成?假设我想根据按钮点击 (href) 在仪表板模板中显示不同的内容。

请提供最佳实践和良好的解决方案,该解决方案易于使用大量组件。

How can i hide/show template components inside the dashboard without creating a new route? Should this be done in helpers using some sort of if/else logic in the html and using helper for on button click?

您可以这样做,但您应该了解一些要点以保持代码整洁和模块化:

  • 尝试将仪表板的一部分包装到自己的模板中以保持代码整洁
  • 使用 ReactiveDict 支持许多 ReactiveVar 个实例
  • 也将模板中的重复部分包装起来以减少重复代码
  • 在全局或仪表板的最上层模板中注册循环助手
  • 在父模板上订阅仪表板所有部分共享的数据,并在各个组件中订阅本地数据
  • 使用 autorunsubscription.ready() 并显示加载指示器,直到订阅准备就绪。不要等到所有内容都加载后再渲染,因为这可能会显着降低用户体验。

Let's say i want to show different content inside dashboard template based on button clicks (href).

您可以将数据属性附加到按钮,该按钮具有要切换的目标的特定 ID:

<template name="dashboardComponent">
  <a href class="toggleButton" data-target="targetId">My Link</a>
</template>

然后您可以读取此 ID 并在 ReactiveDict 中切换它的状态:

Template.dashboardComponent.events({
  'click .toggleButton'(event, templateInstance) {
    event.preventDefault();

    // get the value of 'data-target'
    const targetId = $(event.currentTarget).attr('data-target');

    // get the current toggle state of target by targetId
    const toggleState = templateInstance.state.get( targetId );

    // toggle the state of target by targetId
    templateInstance.state.set( targetId, !toggleState );
  }
});

在您的模板中,您可以要求通过简单的 if / else 呈现:

<template name="dashboardComponent">
  <a href class="toggleButton" data-target="targetId">My Link</a>
  {{#if visible 'targetId'}}
    <div>target is visible</div>
  {{/if}}
</template>

你的助手正在返回状态:

Template.dashboardComponent.helpers({
  visible(targetName) {
    return Template.instance().state.get(targetName);
  }
});

可能存在父子模板之间共享状态的问题,我建议您尽可能避免 Session。然而,作为初学者,首先使用 Session 然后逐步实现更解耦(参数化模板)的解决方案要容易得多。

Please provide a best practice and good solution that is easy with lots of components.

这是一个很高的要求,您有能力同时满足这两个要求!然而,这里有一个简短的内容:

  • 最佳实践是适合您的方法加上在其他用例中也适用于其他人的方法。尝试与他人分享您的工作,看看他们的用例在哪些方面会失败。

  • 使用路由的优势在于,您可以使用查询参数将当前视图状态保存在 url 中。这增加了一个优势,即在重新加载页面或通过 link 共享时,页面状态可以完全恢复。

  • 很多组件很容易是一个矛盾,我不知道你是否期待一些神奇的粉扑来为你解决这个复杂性。作为一名软件工程师,您有能力将复杂性抽象成更小的部分,直到您可以在一定范围内解决问题。