I have a simple store, and I want to have a store value that sums up all the values in an array automatically, but I am unsure what is the best approach with mutations, methods or computed values.
export default {
namespaced: true,
state: {
my_list_values: [10,9,10],
list_sum: 29
}
}
I would like for the list_sum value to function that sums up my_list_values.
CodePudding user response:
You can make use of getter
which holds your logic for listSum
and can be used in components
export default {
namespaced: true,
state: {
my_list_values: [10,9,10],
}
getters: {
listSum (state) {
//logic to sum values
}
}
}
You can use this getter anywhere in your components as below
import { mapGetters } from 'vuex'
computed: {
...mapGetters([
'listSum',
// ...
])
}
OR
this.$store.getters.listSum
For Ref : Getters