Skip to content

Instantly share code, notes, and snippets.

@sotaan
Last active June 30, 2018 00:00
Show Gist options
  • Save sotaan/43920b450170c3a8204434a7aef66fd3 to your computer and use it in GitHub Desktop.
Save sotaan/43920b450170c3a8204434a7aef66fd3 to your computer and use it in GitHub Desktop.
this Vue plugin will create a new computed property with getter/setter binded to a Vuex state property and a mutation
// bind a computed property getter&setter to Vuex state&mutation
// install it with `Vue.use(VuexComputed)` after `Vue.use(Vuex, ...)` line
const VuexComputed = {
install (Vue) {
/**
* computed property factory
* @param {String} statePropName state property name in Vuex store
* @param {String} mutationType name of mutation updating state property
* @param {Number} [debounce=false] wait time argument passed to lodash debounce function
* @return {Object} the new computed property to inject
*/
const createComputed = ({statePropName, mutationType, debounce = false}) => {
const comp = {
get () {
return this.$store.state[statePropName]
}
},
fn = function(newValue) {
this.$store.commit(mutationType, newValue)
},
fnDebounced = _.debounce(fn, debounce)
comp.set = (debounce)? fnDebounced : fn
return comp
}
Vue.mixin({
beforeCreate () {
this.$options.computed = this.$options.computed || {}
Object.keys(this.$options.vuexComputed || {}).forEach(key => {
const options = this.$options.vuexComputed[key]
this.$options.computed[key] = createComputed(options)
})
}
})
}
}
export default VuexComputed
@y4roc
Copy link

y4roc commented Jun 13, 2018

How does it work? Maybe an example?

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