【问题标题】:Re-render templates on route change in Meteor 1.3在 Meteor 1.3 中重新渲染路线变化的模板
【发布时间】:2016-05-09 05:29:31
【问题描述】:

我正在为一个简单的网站使用 Flow Router 和 Blaze Renderer(想想博客/小册子软件)。

我正在使用FlowRouter.path() 在我的菜单元素上创建链接。单击这些链接并触发路由上的action() 方法时,url 会按预期更改。然而,模板似乎没有被刷新,模板助手也没有被触发。

我的 /lib/route.js 文件中的路由是

const about = FlowRouter.group({
  prefix: '/about'
});

about.route('/:pageSlug/:subSectionSlug', {
  action: (params) => {
    console.log('action() fired :' + params.pageSlug + ' :' + params.subSectionSlug);
    BlazeLayout.render( 'applicationLayout', {
      main: 'basicPage',
    });
  },
  name: 'pageSubsection',
});

然后我的模板看起来像 -

<template name="applicationLayout">
        {{> Template.dynamic template=main}}
</template>

<template name="basicPage">
    <div id="pageWrapper">
        ...
        <aside class="leftBar subSectionMenu">
            {{> sidebar }}
        </aside>
        ...
    </div>
</template>

<template name="sidebar">
    <ul class="pageMenu">
        {{#each subSections }}
            {{> sidebarItem}}
        {{/each}}
    </ul>
</template>

<template name="sidebarItem">
    <a class="sidebarItemAnchor" href="{{ href }}">
        <li class="sidebarItem .hoverItem {{#if isSelected }} selected {{/if}}">
            {{title}}
            <span class="sidebarArrow"></span>
        </li>
    </a>
</template>

通过一个简单的助手将selected 类添加到li 元素 -

Template.sidebarItem.helpers({
  href() {
    const subSection = this;
    const params = {
      pageSlug: subSection.pageSlug,
      subSectionSlug: subSection.slug,
    }
    return FlowRouter.path('pageSubsection', params, {});
  },
  isSelected() {
    const slug = FlowRouter.current().params.subSectionSlug;
    console.log('running isSelected with ' + slug);
    if (this.slug === slug) {
      return true;
    } else {
      return false;
    }
  }
});

我想我一定是误解了模板是如何(以及何时)呈现的。

当路由改变时,我需要做什么来重新渲染这些模板?

【问题讨论】:

  • 嗨。你有什么解决办法吗?我希望它在不重新加载完整页面的情况下表现得像正常的路线更改。其他建议是使用 BlazeLayout.reset(),它基本上会重新渲染,但感觉真的很难看&很糟糕

标签: meteor meteor-blaze flow-router


【解决方案1】:

Flow Router 就是这样设计的。它不会自动重新渲染。

一个简单的解决方法是将FlowRouter.watchPathChange(); 添加到依赖于路由参数的所有模板助手中。

所以在这种情况下更新 sidebar.js -

Template.sidebarItem.helpers({
  isSelected() {
    FlowRouter.watchPathChange();
    const slug = FlowRouter.current().params.subSectionSlug;
    if (this.slug === slug) {
      return true;
    } else {
      return false;
    }
  },
});

当在 sidebarItem 模板中使用该助手时,它现在会在路径更改时更新。

【讨论】:

    猜你喜欢
    • 2013-09-02
    • 1970-01-01
    • 2014-03-14
    • 2014-09-22
    • 2015-12-30
    • 2018-08-27
    • 2018-04-20
    • 2014-12-12
    • 1970-01-01
    相关资源
    最近更新 更多