Can’t access my store object from my component

In my store module /store/template.js I have:

const templateConfig = {
  branding: {
    button: {
      secondary: {
        background_color: '#603314',
        background_image: ''
      }
    }
  }
}

export const state = () => ({
  branding: {},
  ...
})

export const actions = {
  initializeStore (state) {
    state.branding = templateConfig.branding
  }
}

(initializeStore() is called when app initially loads)

I want to retrieve the branding the branding object in my component:

computed: {
  ...mapState({
    branding: state => state.template.branding
  })
}

But when trying to console.log() branding I see this:

enter image description here

Why don’t I simply see the branding object? (and what on earth is this?)

Answer

You need to always use a mutation to change state. You can call one from your action:

export const mutations = {
  SET_BRANDING(state, payload) {
    state.branding = payload;
  }
}
export const actions = {
  initializeStore ({ commit }) {
    commit('SET_BRANDING', templateConfig.branding);
  }
}

What you’re seeing with the observer is normal, and indicates that the branding object has been successfully mapped and accessed.

What you see is Vue’s observable object, which is how Vue implements reactivity. Without this, there would be no reactivity, and you will see such a wrapper on all top-level reactive objects. You can pretend it’s not there.

Vue in fact applies this same “wrapper” to the data object internally to make it observable:

Internally, Vue uses this on the object returned by the data function.

You won’t see it on other reactive properties, but if they’re reactive, they belong to some parent observable object.


Leave a Reply

Your email address will not be published. Required fields are marked *