【发布时间】:2021-11-22 21:59:11
【问题描述】:
例如,我有两个列表:收入和结果。我有两个存储(一个用于收入,一个用于结果)。我正在将模块中的这些存储添加到 index.js 中。
我可以为这些收入和结果创建一个存储库,将其显示在列表中并进行计算。但我想为每个单独的商店。
现在的问题是:我怎样才能正确地实现它?我大致做到了。但在这里我只显示和计算INCOME,仅此而已。
如何做得更好?通过 ...mapGetters 在一个组件中导入两个存储以计算并显示在列表中?或者从两个存储中获取数据,并计算 index.js 中的所有内容。然后从 index.js 中获取这些数据?如何在一个组件中使用多个模块?我想在一个组件中显示收入和结果的平衡并显示在列表中。
index.js
import Vue from "vue";
import Vuex from "vuex";
import income from "./modules/income";
import outcome from "./modules/outcome";
Vue.use(Vuex);
export default new Vuex.Store({
state: {},
mutations: {},
actions: {},
modules: {
income,
outcome,
},
});
收入.js
import Vue from "vue";
const income = {
namespaced: true,
state: {
list: {
1: {
type: "INCOME",
value: 100,
comment: "Some comment",
id: 1,
},
},
},
getters: {
incomeList: ({ list }) => list,
},
mutations: {
},
actions: {
},
},
};
export default income;
结果.js
// import Vue from "vue";
const outcome = {
namespaced: true,
state: {
list: {
1: {
type: "OUTCOME",
value: -50,
comment: "Some outcome comment",
id: 2,
},
},
},
getters: {
outcomeList: ({ list }) => list,
},
mutations: {
},
actions: {
},
};
export default outcome;
这是我计算余额的组件
<template>
<div class="total-value" :style="balanceColor">
Balance: {{ totalBalance }}
</div>
</template>
<script>
import {mapGetters} from 'vuex';
export default {
name: 'TBalance',
computed: {
balanceColor: function() {
return {
color: this.totalBalance === 0 ? 'black' : this.totalBalance > 0 ? 'green' : 'red'
}
},
totalBalance() {
return Object.values(this.incomeList).reduce((acc, item) => acc + item.value, 0)
},
...mapGetters("income", ["incomeList"]),
},
methods: {
}
}
</script>
【问题讨论】:
-
为什么不在组件中也使用
...mapGetters("outcome", ["outcomeList"])?
标签: javascript vuejs2 vuex store vuex-modules