Skip to content

Instantly share code, notes, and snippets.

@imyelo
Created May 22, 2020 08:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imyelo/c355279ea4b84bb3c117ccf4b25282d5 to your computer and use it in GitHub Desktop.
Save imyelo/c355279ea4b84bb3c117ccf4b25282d5 to your computer and use it in GitHub Desktop.
write redux as vuex
import _ from 'underscore'
import { combineReducers } from 'redux'
/**
* translate vuex to redux
*/
const translator = {
action: (name) => (action) => (...args) => (dispatch, getState) => {
let state = getState()
return action({
commit: (type, payload) => {
return dispatch({
type,
...payload,
})
},
state: state[name],
rootState: state,
}, ...args)
},
getter: (name) => (getter) => (state) => getter(state[name]),
}
/**
* revuex.reducer for creating store with redux
* revuex.actions for calling in views
* revuex.getters for mapping props into components
*/
export default class Reveux {
constructor ({ modules = {} }) {
let reducers = {}
this.actions = {}
this.getters = {}
_.each(modules, (module, name) => {
this.actions = {...this.actions, ..._.mapObject(module.actions || {}, translator.action(name))}
this.getters = {...this.getters, ..._.mapObject(module.getters || {}, translator.getter(name))}
reducers = {...reducers,
[name]: function reducer (state = module.state || {}, action) {
let mutation = (module.mutations || {})[action.type]
if (mutation) {
return mutation(state, action)
}
return state
}
}
})
this.reducer = combineReducers(reducers)
return this
}
mapActions (map = {}) {
if (map instanceof Array) {
return _.pick(this.actions, ...map)
}
return _.mapObject(map, (name) => {
return this.actions[name]
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment