I use a sortable list connected to a vuex store and get it like:
let nested = computed({
get: () => {
return store.getters.getItems;
}
});
When now changing the order of the elements the store reactively should adapt. When doing a console.log
inside the store like:
console.log(state.line_items_attributes.nested_form);
var temp = cloneDeep(data.nested_form);
state.line_items_attributes.nested_form = temp;
console.log(state.line_items_attributes.nested_form);
The values before and after the assignment are exactly the same.
So it shouldn't matter if I use that mutation or not. But when removing it, and then refreshing the page the store is back to what it was before rearranging the list elements.
CodePudding user response:
As currently written, you don´t mutate your state in vuex
, you mutate it outside of your store, which is the wrong way to do it. In this case, reactivity works from store to component, not the other way round.
In your case, to update your state with the new order, you simply do it like you maybe already doing in other mutations:
CHECK_ORDER: (state, data) => {
state.line_items_attributes = data;
console.log(state.line_items_attributes);
}
Else you should also receive the following error while mutating outside of a mutation:
Error: [vuex] do not mutate vuex store state outside mutation handlers.
Quick tip: Use a copy of your state
If you need to manipulate something outside of your store first and want to mutate the state later, you could get it like this:
this.localItems = JSON.parse(JSON.stringify(store.getters.getItems))
In this case localItems
wont have a reference to your state in the store. As meantioned, vue.draggable.next provides a couple of events you could use to dispatch the sorted object localItems
to the store while doing so.
You can see those events in Events | vue.draggable.next
Small example:
// HTML
<draggable :list="list" @end="onEnd">
// Function
onEnd() {
this.$store.dispatch('myAction', this.localItems)
}
// vuex Action
myAction({commit}, newItems) {
commit('UPDATE_MY_ITEMS', newItems);
}
// vuex Mutation
UPDATE_MY_ITEMS(state,payload) {
state.items = payload;
}