How to set / get objects from vuex state?

Member

by aubrey , in category: Javascript , 3 months ago

How to set / get objects from vuex state?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by addison , 3 months 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.