简体   繁体   English

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

[英]How do you access array data in a computed function with Vue.js

I am new to Vue.js and I can't seem to figure out how to change the format of data. 我是Vue.js的新手,似乎无法弄清楚如何更改数据格式。 Currently it's using the following structure. 当前,它使用以下结构。

app.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: 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 http://codepen.io/pixelasticity/pen/rjeVgz

I want to change the data to the following, or some variation thereof, but it doesn't work. 我想将数据更改为以下内容,或对其进行某些更改,但是它不起作用。

app.js: 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)
    }
  }
})

What am I missing? 我想念什么?

You have to update properties in v-model directives, too. 您还必须更新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>

This ansewers your question. 这回答了您的问题。 However, your data structure seems wired. 但是,您的数据结构似乎是有线的。 Why you need a array here while you sum only first product? 为什么在只累加第一个乘积时需要在这里放置一个数组? Your total computed property do not sum all other products anyway. 无论如何,您的total计算属性不会对所有其他乘积求和。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM