【问题标题】:How do you access array data in a computed function with Vue.js如何使用 Vue.js 在计算函数中访问数组数据
【发布时间】:2017-01-11 22:31:11
【问题描述】:

我是 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)
    }
  }
})

我错过了什么?

【问题讨论】:

  • 为什么将数据更改为 products 数组?
  • 这样我就可以拥有多种不同但仍可调整的价格、运费和折扣的产品。我实际上想在子组件中输入价格。

标签: javascript arrays vue.js vuejs2


【解决方案1】:

您也必须更新 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 计算属性不会对所有其他产品求和。

【讨论】:

  • 谢谢。我知道它必须是那样明显的东西。我希望它采用这种格式的原因是我可以拥有多种具有不同默认价格和运费的产品。
猜你喜欢
  • 2017-08-09
  • 2020-11-17
  • 2019-02-22
  • 1970-01-01
  • 1970-01-01
  • 2018-11-29
  • 1970-01-01
  • 1970-01-01
  • 2016-09-05
相关资源
最近更新 更多