如何使用Vue.js访问计算函数中的数组数据

时间:2017-01-11 22:31:12

标签: javascript arrays vue.js vuejs2

我是Vue.js的新手,我似乎无法弄清楚如何更改数据格式。目前它使用以下结构。

app.js:

new Vue({
  el: '#app',
  data: {
    price: 0,
    shipping: 0,
    handling: 0,
    discount: 0
  },
  computed: {
    total: function () {
      return ((
        this.price * 100 + 
        this.shipping * 100 + 
        this.handling * 100 - 
        this.discount * 100
      ) / 100).toFixed(2)
    }
  }
})

的index.html:

<div id="app" class="row">
  <currency-input label="Price" v-model="price"></currency-input>
  <currency-input label="Shipping" v-model="shipping"></currency-input>
  <currency-input label="Handling" v-model="handling"></currency-input>
  <currency-input label="Discount" v-model="discount"></currency-input>

  <p class="medium-12 columns">Total: ${{ total }}</p>
</div>

http://codepen.io/pixelasticity/pen/rjeVgz

我想将数据更改为以下内容或其中的一些变体,但它不起作用。

app.js:

new Vue({
  el: '#app',
  data: {
    products: [
      {
        price: 0,
        shipping: 0,
        handling: 0,
        discount: 0
      }
    ]
  },
  computed: {
    total: function () {
      return ((
        this.products[0].price * 100 + 
        this.products[0].shipping * 100 + 
        this.products[0].handling * 100 - 
        this.products[0].discount * 100
      ) / 100).toFixed(2)
    }
  }
})

我错过了什么?

1 个答案:

答案 0 :(得分:0)

您还必须更新v-model指令中的属性。

<currency-input label="Price" v-model="products[0].price"></currency-input>
<currency-input label="Shipping" v-model="products[0].shipping"></currency-input>
<currency-input label="Handling" v-model="products[0].handling"></currency-input>
<currency-input label="Discount" v-model="products[0].discount"></currency-input>

这是你的问题。但是,您的数据结构似乎有线。为什么在这里只需要第一个产品时需要一个阵列?您的total计算属性无论如何都不会对所有其他产品求和。

相关问题