【问题标题】:How do I get onRendered to run a second time when the route changes but the template remains the same?当路线更改但模板保持不变时,如何让 onRendered 再次运行?
【发布时间】:2025-12-30 04:20:18
【问题描述】:

我有一个用于更新特定项目数据的 Iron-router 路由:

Router.route('/project/:key/update', {
  ...
});

每次用户导航到“编辑项目页面”时,我都想关注项目名称输入。

template.onRendered(function() {
  this.$('form input[name="project_name"]').focus();
});

这在从仪表板导航到任何给定的编辑项目页面时非常有用。但是,导航到/从一个项目页面到另一个项目页面时,onRendered 函数不会重新运行,因此输入没有聚焦。

【问题讨论】:

    标签: meteor iron-router


    【解决方案1】:

    您可以通过在autorun 中添加对currentData 的检查来强制onRendered 在上下文更改后重新评估,如下所示:

    Template.myTemplate.onRendered(function() {
      var self = this;
      this.autorun(function() {
        // hack to force the autorun to reevaluate
        Template.currentData();
    
        // insert onRendered code here
        self.$('form input[name="project_name"]').focus();
      });
    });
    

    更多详情见this issue末尾。

    【讨论】:

    • 谢谢!我已阅读您对 SO 上类似问题的回答,但我错过了 self 部分。
    最近更新 更多