如何在Vue中的一组单选按钮中绑定除值之外的额外数据?

时间:2018-04-12 10:04:39

标签: javascript vue.js

我使用Vue创建一个带有价目表的产品表。基本上,我有一组单选按钮,我用它来更改产品,然后显示该特定产品的价格列表。 它有效,但除了id之外,我想获得每个产品的附加数据。我试图绑定一个属性hasFrame,但我不确定如何使用它。

这是产品列表的html:

<ul>
<li v-for="productType in productTypes"
    v-bind:class="{'is-selected': isSelected(productType.id) }">
  <label>
    <input type="radio"
           class="o-radio-hidden"
           name="product-type"
           v-model="selectedProductType"
           @change="changeProduct(productType)"
           v-bind:value="productType.id"
           v-bind:hasFrame="productType.has_frame">
    <span class="product-name">{{ productType.name }}</span>
  </label>
</li>
</ul>

然后在html中有一张表格,我会显示价格,但它与我在这里的问题没有关系,所以我把它遗漏了。

这是Javascript部分:

  let vf = new Vue({
    el: '#product-table',
    data: {
      productTypes: [],
      productType: [],
      selectedProductType: [],
      hasFrame: 0,
    },
    methods: {
       getProductTypesList() {
           axiosInstance.get('ajax/getProductTypesList')
               .then((response) => {
                   this.productTypes = response.data;
           });
      },
      isSelected(productTypeId) {
        return productTypeId === this.selectedProductType;
      },
      changeProduct(productType) {
        this.hasFrame = productType.has_frame; // how to avoid this?
        this.getProductsData();
      },
    mounted() {
      this.selectedProductType = currentProductTypeId || 5;
      this.getProductTypesList();
      this.getProductsData();
    },
  });

方法getProductTypesList()返回具有以下结构的对象数组:

{
  "name": "Product name",
  "id": 1,
  "has_frame": 1 // boolean
}

因此,在changeProduct内,我手动更新了属性hasFrame。有没有办法避免它并让产品在产品发生变化时自动更改?

1 个答案:

答案 0 :(得分:0)

您将productType声明为data项,但未设置它。同样,您声明hasFrame,但不使用它。你绑定productType.has_frame(其中productType是一个参数,而不是data项),这应该可以正常工作。

changeProduct应设置this.productType(不应该是数组)。然后hasFrame,如果您希望能够引用它而不是this.productType.has_frame,则可能是一个简单的计算:

hasFrame() {
  return this.productType.has_frame;
}