Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vue.js/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何计算篮子Vuejs Vuex的总价_Javascript_Vue.js_Vuejs2_Vuex - Fatal编程技术网

Javascript 如何计算篮子Vuejs Vuex的总价

Javascript 如何计算篮子Vuejs Vuex的总价,javascript,vue.js,vuejs2,vuex,Javascript,Vue.js,Vuejs2,Vuex,我有一个商店,其中有一个名为basketContents 像这样: state: { basketContents: [ { name: ..... quantity: 2 price:1000 }, { name: ..... quantity: 6 price:120 }, ......... ] } 从这里,我想计算整个篮子的总价格,并将其显示在一个组件中。有没有简单的方法可以做到这一点?每当我改变物品数量时,总价格也应该

我有一个商店,其中有一个名为
basketContents

像这样:

state: {
basketContents: [
{
     name: .....
     quantity: 2
     price:1000
},
{
     name: .....
     quantity: 6
     price:120
},
.........
   ]
}
从这里,我想计算整个篮子的总价格,并将其显示在一个组件中。有没有简单的方法可以做到这一点?每当我改变物品数量时,总价格也应该改变。
我不熟悉这一点。

在要显示总价的组件的计算中创建一个名为totalPrice的函数:

  computed: {
   totalPrice() {
      return this.$store.state.basketContents.reduce(
        (acc, val) => acc + val.quantity * val.price,
        0
      );
    },
  },
};
在你的getter中,你可以添加这个

.vue
文件中,放入:

import { mapGetters } from 'vuex';
// And put in computed:
// mix the getters into computed with object spread operator
...mapGetters([
   'total'
])

let total=state.basketContents.reduce((acc,val)=>acc+val.quantity*val.price,0)
。。。在你的代码之后,你也有错误,比如在
状态之后应该有
=
,如果这是一个变量,而且object中的属性之后没有逗号,谢谢,我会给出答案。
import { mapGetters } from 'vuex';
// And put in computed:
// mix the getters into computed with object spread operator
...mapGetters([
   'total'
])