Last active
June 30, 2018 00:00
-
-
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
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
// 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How does it work? Maybe an example?