如何使Iron:router重新渲染模板?

我有这个HTML:

<head>
</head>

<body>
</body>

<template name="mainLayout">
  <a href="{{pathFor route='list'}}">list</a>
  <a href="{{pathFor route='find' query='q=xxx'}}">find</a>
  {{> yield}}
</template>


<template name="listTemplate">
  <p>list</p>
</template>

和这个js:
Router.configure({
    layoutTemplate: 'mainLayout'
});

Router.route('/list', {
    name: 'list',
    template: 'listTemplate'
});

Router.route('/find', {
    name: 'find',
    template: 'listTemplate',
    data: function () {
        return this.params.query;
    }
});


if (Meteor.isClient) {
    Template.listTemplate.rendered = function () {
        if (this.data)
            console.log('find ' + this.data.q);
        else
            console.log('list all');
    };
}

当我单击链接以切换 View 时(此处在console.log中进行了模拟),路由确实发生了变化,但是模板没有重新呈现。
有没有办法强制iron:router重新渲染?

最佳答案

您可以尝试如下操作:

Router.configure({
  layoutTemplate: 'mainLayout'
});

Router.route('/list', {
  name: 'list',
  template: 'listTemplate',
  action: function() {
    this.state.set('query', this.params.query);
  }
});

Router.route('/find', {
  name: 'find',
  template: 'listTemplate',
  data: function() {
    return this.params.query;
  },
  action: function() {
    this.state.set('query', this.params.query);
  }
});


if (Meteor.isClient) {
  Template.listTemplate.rendered = function() {
    this.autorun(
      function() {
        if (this.state.get('query'))
          console.log('find ' + this.data.q);
        else
          console.log('list all');
      }
    );
  };
}

呈现的方法不是被动的,这就是为什么您需要自动运行的原因。
模板“this.data”不是响应式(Reactive)的,因此您将需要一个响应式(Reactive)var来执行此操作,无论是Session变量, Controller 状态还是某种响应式(Reactive)var。

根据您采用的方法,您可能需要添加react-var软件包。

关于meteor - 铁:router will not re-render after route change with same template,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26970808/

10-11 12:56
查看更多