Reputation: 3075
if I attempt to pass the namespace as the first argument, as suggested by the docs, I get "undefined" as the value ('test' is set in the module definition)
...mapState('guest', {
email: state => state.email,
}),
but it works fine if I just do it this way without the namespace as the first argument
...mapState({
email: state => state.guest.email,
}),
I would like to use the shortcut and according to the documentation, the first example should be working... right?
https://vuex.vuejs.org/guide/modules.html#binding-helpers-with-namespace
Here is my module definition:
const initialState = function(){
let state = {
email: null,
};
return state;
};
export default {
namespaced: true,
state: initialState(),
mutations: {
fill(state, data) {
Object.assign(state, data);
},
reset(state) {
Object.assign(state, initialState());
}
},
actions: {
}
};
Upvotes: 2
Views: 584
Reputation: 23463
Your computed...mapState
syntax is correct, so likely the problem is with the way the fill mutation is called. Are you namespacing the commit?
This is a working example.
The only other thing to change is state: initialState
should be state: Object.assign({}, initialState)
.
The first way sets state to a reference to the initialState
object, so any changes in the fill mutation will over-write the values of initialState
, and the reset mutation will have no effect.
Component
export default {
...
computed: {
...mapState("guest", {
email: state => state.email
})
},
mounted() {
// Call the fill mutation with namespace
this.$store.commit("guest/fill", {
email: "some@email"
});
// Call reset after 2 seconds
setTimeout(() => {
this.$store.commit("guest/reset");
}, 2000);
}
Store
const initialState = {
name: "dummyName",
email: "dummy@initial" // put a value here so we can see if mapState works
};
const store = new Vuex.Store({
modules: {
guest: {
namespaced: true,
state: Object.assign({}, initialState),
mutations: {
fill(state, data) {
Object.assign(state, data);
},
reset(state) {
Object.assign(state, initialState);
}
}
}
}
});
Upvotes: 2