iron:router will not re-render after route change with same template

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-04 02:53:27

You can try something like this:

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');
      }
    );
  };
}

The rendered method isn't reactive, that's why you need an autorun. The template "this.data" isn't reactive so you're gonna need a reactive var to do that, either a Session variable, a controller state, or some kind of reactive var.

You may need to add the reactive-var package depending on what approach you take.

Setting the router controller state did not work for me. The answer Antônio Augusto Morais gave in this related github issue worked. Using the Session to store the reactive var to trigger the autorun reactiveness. It's a hack, but it works.

## router.coffee
Router.route '/profile/:_id',
  name: 'profile'
  action: ->
    Session.set 'profileId', @params._id
    @render 'profile'

## profile.coffee
Template.profile.onCreated ->
  @user = new ReactiveVar
  template = @

  @autorun ->
    template.subscription = template.subscribe 'profile', Session.get 'profileId'

    if template.subscription.ready()
      template.user.set Meteor.users.findOne _id: Session.get 'profileId'
    else
      console.log 'Profile subscription is not ready'

Template.profile.helpers
  user: -> Template.instance().user.get()

## profile.html
<template name="profile">
  {{#if user}}
    {{#with user.profile}}
      <span class="first-name">{{firstName}}</span>
      <span class="last-name">{{lastName}}</span>
    {{/with}}
  {{else}}
    <span class="warning">User not found.</span>
  {{/if}}
</template>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!