0

我一直在 VUE.js 中构建这个应用程序,但是在一个函数上有一个小问题,我试图在数组中添加每个对象的值..给我一个 NaN 错误。让我们说

script

data(){
 return{
    array:[
      { product_name: "Chain Saw",
       product_free: 2,
       product_free_discount: 306.8,
       product_id: 1,
      }
      { product_name: "Ox",
       product_free: 1,
       product_free_discount: 60.8,
       product_id: 1,
      }
  ],
  totalDiscEquals:0,
 }
}

然后在我的计算属性上,我只是设置了这个函数

COMPUTED
totalDiscObUnique() {
      let total = this.array.reduce(

        (a, b) => a + b.product_free_discount,
        0
      );
      console.log(total);

      return this.totalDiscEquals=total;
    },

像这样在创建的模块中创建进程

created(){
this.totalDiscObUnique;

但是当我控制台记录totalDisEquals 的值时,会抛出一个NaN 结果,任何关于为什么会发生这种情况的想法,或者关于为什么NaN 经常出现的原因?

4

1 回答 1

0

new Vue({
  el: '#app',
  
  data: {
    array:[
      { 
        product_name: "Chain Saw",
        product_free: 2,
        product_free_discount: 306.8,
        product_id: 1,
      }, // <--- [1] missing comma here (,)
      { 
        product_name: "Ox",
        product_free: 1,
        product_free_discount: 60.8,
        product_id: 1,
      }
    ],
    totalDiscEquals:0,
  },
  
  /* [2] It's not recommended to assign new value to a data property
 in a computed, instead it intended to give you just a filtered / reduced
 / ... response.  */
  computed: {
    totalDiscObUnique() {
      return this.array.reduce((a, b) => a + b.product_free_discount, 0);
    },
  },
  
  created () {
    /* [3] also, there is no need to reassign the same value to a new
 data property again, instead you can use the computed itself wherever you
 want to use it */
    // this.totalDiscEquals = this.totalDiscObUnique
    console.log(this.totalDiscObUnique)
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
 {{ totalDiscObUnique }}
</div>

于 2020-04-02T10:41:13.043 回答