Imagine you have to calculate the total sum of specific numbers (in this case, IDs) retrieved from a database.
Laravel/api:
[
{ "id": 3, "created_at": null, "updated_at": null, "name": "Name One" },
{ "id": 4, "created_at": null, "updated_at": null, "name": "Name Two" }
]
Component:
<template>
<div class="font-semibold text-4xl text-gray-600">
{{showTotal}}
</div>
import {mapGetters, mapActions} from 'vuex';
export default {
name: "Total",
mounted() {
this.fetchNames();
},
methods: {
...mapActions(["fetchNames"])
},
computed: {
...mapGetters(["getNames"]),
showTotal() {
return this.getNames[0]['id'] + this.getNames[1]['id']
}
},
}
In the console, there were errors reported. However, Vue.js devtools showed the correct total value as 7. Here are the screenshots for reference: Vue.js devtools and Console errors.
store/modules/names.js:
export default {
state: {
names: [],
},
getters: {
getNames: state => state.names,
},
actions: {
async fetchNames({commit}) {
const response = await axios.get('/api/names');
commit('setNames', response.data);
},
},
mutations: {
setNames: (state, names) => state.names = names,
}
}