Created
May 22, 2020 08:25
-
-
Save imyelo/c355279ea4b84bb3c117ccf4b25282d5 to your computer and use it in GitHub Desktop.
write redux as vuex
This file contains hidden or 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
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