流星:如何设置数组值,在空格内,动态

Meteor: how to set array value, within spacebars, dynamically

本文关键字:空格 动态 数组 何设置 设置 流星      更新时间:2023-09-26

我真的不知道如何解释这个…我有一个集合,里面有一个数组当我遍历它的时候,我一直在设置颜色。[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();
}

您要做的一种方法是定义一个以colorsviewIndex为参数的colorPrice助手,如下所示:

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>

所以感谢Kalman让我想到一种使用更多javascript的动态方法!我的解决方案本质上是通过调用{{#with item}}中的helper函数来使用helper和"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}}

(helper函数)
variationIndex(index) {
  return index+1;
}

(事件函数设置变化值)

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