【问题标题】:Meteor: how to set array value, within spacebars, dynamicallyMeteor:如何在空格键内动态设置数组值
【发布时间】:2016-12-16 01:23:48
【问题描述】:

我真的不知道如何解释这个...我有一个集合,其中有一个数组,当我浏览它时,我一直在设置颜色。[0].imageLink 而不是更改 [0 ],但现在我希望它是动态的,取决于函数的值(在这种情况下,函数是 viewIndex)。

有效,但不是动态的:

<h3 class='display-price'>$ {{colors.[0].price}}</h3>

我认为可行但行不通的方法:

<h3 class='display-price'>$ {{colors.[(viewIndex)].price}}</h3>

在对应的js文件中(确实返回0):

'viewIndex': function() {
  console.log(Template.instance().variation.get());
  return Template.instance().variation.get();
}

【问题讨论】:

  • 你试过没有括号吗?即$ {{colors.[viewIndex].price}}。我不使用 Meteor 或 Spacebars 模板,所以我只是在猜测。
  • 您能否详细解释一下您实际上想要做什么?这是一种奇怪的模式——很少需要在显示循环中使用索引来访问元素。
  • 是的,我试过不带括号,带括号,不带括号 - 几乎所有东西。我试图通过单击下拉菜单来更改项目的基本变体。

标签: javascript html meteor spacebars


【解决方案1】:

做你想做的事情的一种方法是定义一个colorPrice帮助器,它接受colorsviewIndex作为参数,如下所示:

Template.hello.helpers({
  colors() {
    return [
      { price: 1},
      { price: 2},
      { price: 3}
    ];
  },
  viewIndex(){
    return 1;
  },
  colorPrice(colors, viewIndex){
    return colors[viewIndex].price;
  }
});

然后,在您的模板中,您可以按如下方式使用它:

<template name="hello">
  ${{ colorPrice colors viewIndex }}
</template>

【讨论】:

  • 这不是很动态,因为值是从具有不同数量颜色变化的集合中传递出来的,但它确实导致找到了解决方案,所以谢谢 :)
【解决方案2】:

感谢 Kalman 让我想到了一种使用更多 javascript 的动态方法!我的解决方案本质上是通过在 {{#with item}} 中调用辅助函数来使用辅助函数和“this”关键字,它传递了“this”它所在的当前项目的所有值,所以基本上这成为可能:

variationImage() {
  return this.colors[Template.instance().variation.get()].imageLink[0];
},
variationLink() {
  return this.colors[Template.instance().variation.get()].referralLink;
},
variationPrice() {
  return this.colors[Template.instance().variation.get()].price;
}

那时获取这些值就像在我需要价格的地方使用 {{variationPrice}} 等一样简单。

{{#with item}}
  <h3 class='display-price'>$ {{variationPrice}}</h3>
{{/with}}

并且只是为了添加更多关于变体如何工作的信息,每个项目都有几乎随机数量的变体(因为我们刮掉了它们)所以我们必须按照这些方式做一些事情来渲染有多少并设置你的变体'再看:

(其中 colors 是一个包含项目不同颜色变化的数组)

{{#each colors}}
  <option value='{{@index}}'>Variation {{variationIndex @index}}</option>
{{/each}}

(辅助函数)

variationIndex(index) {
  return index+1;
}

(设置变化值的事件函数)

'change .color-variation-select': function(event, template) {
  template.variation.set($(event.target).val());
},

【讨论】:

    猜你喜欢
    • 2011-04-11
    • 1970-01-01
    • 2015-12-30
    • 2015-07-03
    • 2020-01-31
    • 2018-07-23
    • 1970-01-01
    • 2019-01-11
    相关资源
    最近更新 更多