Last active
August 26, 2022 07:24
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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