Reputation: 51
I'm exploring vuex modules feature and I can't figure out what I do wrong.
I have a simple vuex store with one module.
The module contains a state and mutation option, where just adding a new item in the module state.
When I trying to call the mutation function, it doesn't work.
Codesandbox => https://codesandbox.io/s/currying-fire-2p3eq?file=/src/App.vue
Upvotes: 0
Views: 103
Reputation: 63059
Your action has combined the context and payload arguments into one instead of keeping them separate:
addItem({ commit }, payload) { ✅ // Correct
addItem({ commit, payload }) { ❌ // Incorrect
Another problem is your module's state
is an array instead of an object, and is being used directly, as if it was a state item. Make state
an object, and put the item data into an array property:
state: {
items: [
{ id: "1", name: "1" },
{ id: "2", name: "2" },
{ id: "3", name: "3" }
]
}
Change your computed to use this items
property:
const ItemsState = computed(() => store.state.a.items);
In the mutation, push the new value (what you had before would not change state
at all because it just changes the function argument reference):
SET_NEW_ITEM(state, payload) {
state.items.push(payload);
}
You don't need an action to call this:
function addItem() {
let newItem = { id: "5", name: "5" };
store.commit('a/SET_NEW_ITEM', newItem)
}
Here is your updated sandbox
Upvotes: 0
Reputation:
you have to call from the actions
const addTheme = ({ commit }, { description }) => {
commit(SET_NEW_ITEM, {
description
});
...
}
and in mutation you have to create a function with the same name SET_NEW_ITEM:
const SET_NEW_ITEM = (state, description) => {
}
Upvotes: 2