Skip to content

Instantly share code, notes, and snippets.

@l-portet
Last active August 26, 2022 07:24
Show Gist options
  • Save l-portet/6a861c6f85dd764af361c26982ac5c26 to your computer and use it in GitHub Desktop.
Save l-portet/6a861c6f85dd764af361c26982ac5c26 to your computer and use it in GitHub Desktop.
Edit all nested props of a Vuex state with a single mutation
// Usage:
// commit ('SET', { prop: `path.to['my'].prop[1]`, value: 42 });
// or commit ('SET', [`path.to['my'].prop[1]`, 42]);
export default {
SET_PROP(state, payload) {
let prop, value;
if (Array.isArray(payload)) {
[prop, value] = payload;
} else {
({ prop, value } = payload);
}
const path = prop.replace(/\['?(\w+)\'?]/g, '.$1').split('.');
let current = state;
while (path.length > 1) {
current = current[path.shift()];
}
current[path[0]] = value;
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment