Search code examples
javascriptvue.jsvuejs2vuex

How to use functions in Vuex state creation


I am trying to set part of my state using a getter which I later define

export const store = new Vuex.Store({
  state : {
    a : 1,
    b : getters.multiply(a)
  },
  getters : {
    multiply : (state) => (param) => return param * 2
  },
})

This is not allowed as the getters are not ready (I think).

The docs do state that the Vuex state property can take a function to create the data - but I have not seen any examples, does the full state need to be initialised by function call or some props.

Any help appreciated.


Solution

  • Normally getters is method to get state data. It should not be 2 ways. In above example, you can do:

    const multiply = (params) => params * 2
    const INIT_VALUE = 1
    
    export const store = new Vuex.Store({
      state : {
        a : INIT_VALUE,
        b : multiply(INIT_VALUE)
      }
    })