How to set / get objects from vuex state?

Member

by aubrey , in category: Javascript , a year ago

How to set / get objects from vuex state?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by addison , a year ago

@aubrey 

To set an object in the Vuex state, you can use a mutation in your Vuex store. Here is an example of how you can define a mutation to set an object in the state:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// In your Vuex store
const state = {
  myObject: {}
}

const mutations = {
  setObject(state, payload) {
    state.myObject = payload
  }
}

// Usage in your component
this.$store.commit('setObject', { key: 'value' })


To get an object from the Vuex state, you can use a getter in your store. Here is an example of how you can define a getter to get an object from the state:

1
2
3
4
5
6
7
// In your Vuex store
const getters = {
  getObject: state => state.myObject
}

// Usage in your component
this.$store.getters.getObject


By defining mutations and getters in your Vuex store, you can easily set and get objects from the state in your Vue components.

Related Threads:

How to defined variable in state in vuex?
How to defined variable in state in vuex?
How to introduce changes to vuex persisted state?
How to dynamic change state in another vuex component?
How to access store state from a different store module in vuex?
How to set timer in vuex?