Skip to content

Instantly share code, notes, and snippets.

@joernroeder
Last active July 6, 2018 13:51
Show Gist options
  • Save joernroeder/4806b579864d3ff4c35171cc51afcbb8 to your computer and use it in GitHub Desktop.
Save joernroeder/4806b579864d3ff4c35171cc51afcbb8 to your computer and use it in GitHub Desktop.
Add Vuex Model
/*
* Adds a computed property name to your component which uses the specified getter and actionName for reactivity.
* Afterwards you can bind the property name to e.g. form elements like any other property via `v-model`.
* See https://vuejs.org/v2/guide/forms.html for more details
*
* import addVuexModel from './utils/addVuexModel'
* {
* computed: {
* ...addVuexModel({
* name: 'propertyName',
* getter: 'getterName',
* action: 'actionName',
* namespace: 'optional namespace of your vuex module'
* })
* }
* }
*/
export default ({ name, getter: getterName, action: actionName, namespace }) => {
const namespaced = namespace ? `${namespace}/` : ''
const getter = getterName || name
const action = actionName || name
return {
[name]: {
get () {
return this.$store.getters[namespaced + getter]
},
set (value) {
this.$store.dispatch(namespaced + action, value)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment