Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamic store value in Vuex

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading