Skip to content

Instantly share code, notes, and snippets.

@jakedowns
Last active June 9, 2020 16:22
Show Gist options
  • Save jakedowns/67347232f53c9fd413ec6d314744d62e to your computer and use it in GitHub Desktop.
Save jakedowns/67347232f53c9fd413ec6d314744d62e to your computer and use it in GitHub Desktop.
Vuex MapGetSet Helper - useful for binding Vuex Store property to v-model
<script>
/*
easily map vuex store fields with a generic getter and setter (assumes mutation exists: field name; all caps, with SET_ prefix)
assumes setter is top level property, not deeply nested
so you can easily use the field with v-model="field"
*/
window.mapGetSet = function(module_name,array_of_props){
let out = {};
_.map(array_of_props,(prop)=>{
out[prop] = {
get () {
return this.$store.state[module_name][prop];
},
set (value) {
const mutationName = 'SET_'+prop.toUpperCase();
this.$store.commit(`${module_name}/${mutationName}`, value);
}
}
})
return out;
}
/* --- */
export default {
name: "MyComponent",
components: {
//
},
data(){
return {
//
}
},
computed:{
...mapState('module',[
'read_only_field_A',
]),
/*
map store fields with getter and setter (assumed mutation: field name; all caps, with SET_ prefix)
so you can easily use the field with v-model="field"
*/
...mapGetSet.call(this,'module',[
'readable_writable_field_B',
])
}
}
const makeBasicMutators = function(props){
let out = {};
_.map(props,prop=>{
const mutationName = 'SET_'+prop.toUpperCase();
out[mutationName] = (state, value) => {
state[prop] = value;
}
})
return out;
}
/* Store: */
export default {
state: {
read_only_field_A: 'foo',
readable_writable_field_B: 'bar'
},
mutations: {
SET_READABLE_WRITABLE_FIELD_B(state, value){
state.readable_writable_field_B = value;
},
// or
...makeBasicMutators([
'readable_writable_field_B',
])
}
</script>
@jakedowns
Copy link
Author

jakedowns commented Jun 9, 2020

A. this is only built for Vuex stores using modules, it would need tweaked for generic top-level store support
B. checkout makeBasicMutators, you pass it an array of property names, and it generates all caps SET_X mutators

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment