0

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.