'How to set / retrieve objects from Vuex state
In the following code snippet, why and how do the state and man return empty while I can still access a property of the man object?
note: The code snippet is a module that is part of a module that is imported into another file in which the store is created.
class Man {
constructor(firstName, lastName) {
this.firstName = firstName
this.lastName = lastName
}
}
const state = {
man: undefined,
}
const mutations = {
setMan(state, data) {
state.man = new Man(
data.firstName,
data.lastName
)
console.log("state: " + JSON.stringify(state)) // state: {}
console.log("man: " + JSON.stringify(state.man)) // man: {}
console.log("first name: " + state.man.firstName) // John
}
}
commit('setMan', {
firstName: "John",
lastName: "Snow"
})
Solution 1:[1]
The state, mutations should actually be properties of the store configs. There you declare the properties but they are not wrapped in the Vuex store.
You might want to check this page of the doc that explains it: https://vuex.vuejs.org/guide/#the-simplest-store.
(Here you are missing the createStore part.)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
