Last active
February 5, 2021 05:09
-
-
Save lmiller1990/a6afeef04cec494cee4abb6ec3c305bb to your computer and use it in GitHub Desktop.
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
import { reactive, computed } from 'vue' | |
const registerModules = (modules, state) => { | |
for (const [name, module] of Object.entries(modules)) { | |
state[name] = module.state | |
if (module.modules) { | |
registerModules(module.modules, module.state) | |
} | |
} | |
return state | |
} | |
class Store { | |
constructor(options) { | |
let state = options.state | |
if (options.modules) { | |
state = registerModules(options.modules, state) | |
} | |
if (options.state) { | |
this.state = reactive(state) | |
} | |
if (options.mutations) { | |
this.mutations = options.mutations | |
} | |
if (options.actions) { | |
this.actions = options.actions | |
} | |
if (options.getters) { | |
this.getters = {} | |
const { getters } = options | |
for (const [handle, fn] of Object.entries(getters)) { | |
Object.defineProperty(this.getters, handle, { | |
get: () => computed(() => fn(this.state)).value | |
}) | |
} | |
} | |
} | |
commit(handle, payload) { | |
this.mutations[handle](this.state, payload) | |
} | |
dispatch(handle, payload) { | |
const call =this.actions[handle](this, payload) | |
if (!call || !call.then) { | |
return Promise.resolve(call) | |
} | |
} | |
} | |
export const Vuex = { | |
Store | |
} | |
import { Vuex } from './' | |
const createStore = () => new Vuex.Store({ | |
state: { | |
count: 1 | |
}, | |
mutations: { | |
INCREMENT(state, payload) { | |
state.count += payload | |
} | |
}, | |
actions: { | |
increment(context, payload) { | |
context.commit('INCREMENT', payload) | |
} | |
}, | |
getters: { | |
triple: state => state.count * 3 | |
} | |
}) | |
test('commits a mutation', () => { | |
const store = createStore() | |
store.commit('INCREMENT', 5) | |
expect(store.state.count).toBe(6) | |
}) | |
test('dispatches an action', () => { | |
const store = createStore() | |
return store.dispatch('increment', 5).then(() => { | |
expect(store.state.count).toBe(6) | |
}) | |
}) | |
test('getters are computed', () => { | |
const store = createStore() | |
expect(store.getters['triple']).toBe(3) | |
store.state.count += 1 | |
expect(store.getters['triple']).toBe(6) | |
}) | |
test('is has nested state', () => { | |
const store = new Vuex.Store({ | |
state: {}, | |
modules: { | |
levelOne: { | |
state: {}, | |
modules: { | |
levelTwo: { | |
state: { name: 'level two' } | |
} | |
} | |
} | |
} | |
}) | |
expect(store.state.levelOne.levelTwo.name).toBe('level two') | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment