I have been exploring ways to utilize Vue.set()
to dynamically modify bound data within Vuex store. After some trial and error, I came up with a solution that has been working for me.
Please note that the code may not be the most elegant.
This is my current solution:
mutations: {
add_to_store(state, [route, key, value]){
const call_vue_set_with_dynamic_params = new Function(
"Vue",
"state",
"route",
"key",
"value",
`Vue.set(state${route === "" ? "" : `.${route}`}, key, value)`
);
call_vue_set_with_dynamic_params(Vue, state, route, key, value)
}
}
If anyone has some time to spare, it might be interesting to try and optimize this code further as I am currently feeling a bit stuck.
I attempted to pass the found object into Vue.set()
like this:
const create_nested_object = ( base, names ) => {
names.split(".").forEach(name => {
base = base[ name ] = base[ name ] || {}
})
return base
}
mutations: {
add_to_store(state, [route, key, value]){
Vue.set(
create_nested_object(state, route),
key,
value
)
}
}
Unfortunately, this approach did not work as expected. I also experimented with overwriting the entire state
with a new one, but this caused reactivity issues.
The ultimate goal of this mutation is to take a string specifying the route to the desired object like: user.hair.color
and update it with the desired value.
The intention is to avoid creating separate mutations for each key individually.