【问题标题】:Meteor - Reloading template section after variable changeMeteor - 变量更改后重新加载模板部分
【发布时间】:2018-10-31 02:41:27
【问题描述】:

我想在变量更改后刷新/重新加载模板的一部分,以便如果变量为真,它会显示内容 A,否则它将显示内容 B。我确信这是一个非常简单的问题,但我我在寻找解决方案时遇到了麻烦。

类似这样的:

Template.x.created = function() {
    this.variable = false;
}

Template.x.helpers({
    'getValue': function(){
            return this.variable;
        }
});

模板:

<template name="x"> 
    {{#if getValue}}
     <content A>
    {{else}}
     <content B>
    {{/if}}
</template>

【问题讨论】:

    标签: meteor meteor-blaze


    【解决方案1】:

    您需要创建一个响应式数据源以在变量更改时让模板助手重新运行,因为普通变量不会让助手知道它何时更改值。最简单的解决方案是使用ReactiveVar

    Template.x.onCreated(function() {
      this.variable = new ReactiveVar(false);
    });
    
    Template.x.helpers({
      'getValue': function() {
        // Note that 'this' inside a template helper may not refer to the template instance
        return Template.instance().variable.get();
      }
    });
    

    如果您需要在此模板之外的某个位置访问该值,您可以使用 Session 作为替代的反应式数据源。

    【讨论】:

      【解决方案2】:

      @Waiski 的回答很好,但我想分享一个我构建的简单模板助手,因为很多模板都需要这个:

      使用registerHelper,您可以像这样构建一个全局助手:

      Template.registerHelper('get', function (key) {
        let obj = Template.instance()[key]
        return (obj && obj.get) ? obj.get() : obj
      })
      

      在每个模板中使用它:

      Template.x.onCreated(function() {
        this.foo = new ReactiveVar(true)
        this.bar = new ReactiveVar('abc')
      })
      

      HTML:

      {{#let foo=(get 'foo')}}
        {{#if get 'bar'}}
          Bar is true. Foo: {{foo}}
        {{/if}}
      {{/let}}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-07
        • 2014-04-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-21
        • 1970-01-01
        相关资源
        最近更新 更多