【问题标题】:Create multiple instances of components in Meteor JS在 Meteor JS 中创建多个组件实例
【发布时间】:2018-11-25 17:48:10
【问题描述】:

我正在创建按钮、文本字段等元素,作为不同模板中的组件。如何在我的项目中的表单(模板)上创建此组件的多个实例?一个例子是在一个页面上使用多个文本字段。

假设我想创建一个注册页面,我需要 3 个文本字段、2 个按钮,如何创建它们?

这是一个示例:

<template name="mybutton">
    <input type="button" name="{{butonname}}" class="{{buttonclass}}" placeholder="{{buttonplaceholder}}">
</template>

<template name="mytext">
    <input type="text" name="{{textname}}" class="{{textclass}}" placeholder="{{textplaceholder}}">
</template>

<template name="signup">
    {{> Template.dynamic template=getTemplateName }}
</template>

Template.signup.onCreated(funtion(){
    this.state = new ReactiveDict();
    this.state.set('targetTemplate', 'mybutton');
})

Template.sidebar.helpers({
    getTemplateName(){
        return Template.instance().state.get("targetTemplate");
    }
})

【问题讨论】:

  • 使用Template.dynamic而不是直接调用你的模板的原因是什么?
  • 我在运行时在同一帧中加载不同的模板。加载所有模板会破坏我想要实现的可重用性的目的。
  • 您应该描述您的限制条件,否则可能的答案将无法满足。

标签: templates meteor meteor-blaze multiple-instances


【解决方案1】:

不知道你打算做什么,但如果我猜对了,你想在一个模板中渲染多个动态模板!?

如果是这样,那么您还需要多个动态响应式数据源:

<template name="signup">
    {{> Template.dynamic template=getPrimaryTemplate }}
    {{> Template.dynamic template=getSecondaryTemplate }}
</template>


Template.signup.onCreated(function(){
    this.state = new ReactiveDict();
    this.state.set('primaryTemplate', 'mybutton');
    this.state.set('secondaryTemplate', 'myText');
})

Template.sidebar.helpers({
    getPrimaryTemplate(){
        return Template.instance().state.get("primaryTemplate");
    },
    getSecondaryTemplate(){
        return Template.instance().state.get("secondaryTemplate");
    },
});

更通用的方法:如果您必须处理许多动态模板,您也可以将其包装到单个帮助器中:

<template name="signup">
    {{> Template.dynamic template=(getTemplate 'header') }}

    {{> Template.dynamic template=(getTemplate 'body') }}

    {{> Template.dynamic template=(getTemplate 'footer') }}
</template>


Template.signup.onCreated(function(){
    this.state = new ReactiveDict();
    this.state.set('header', 'mybutton');
    this.state.set('body', 'myText');
    this.state.set('footer', 'someOtherTemplate');
})

Template.sidebar.helpers({
    getTemplate(templateName) {
        return Template.instance().state.get(templateName);
    }
});

【讨论】:

    【解决方案2】:

    在 blaze 中,您可以根据需要多次包含模板 - 我不确定您在寻找什么 - 您的问题并不完全清楚。

    {{> mytext }}
    {{> mybutton }}
    {{> mytext }}
    {{> mytext }}
    {{> mybutton }}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-08
      • 2018-10-22
      • 2016-04-06
      • 2022-12-29
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多