-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
77 lines (71 loc) · 1.6 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
* 极简组件状态管理library,inspired by redux & vuex
* */
let Vue
export const createStore = (reducers) => {
let state = {}
const initType = '___init___'
const subscribers = []
function subscribe(fn) {
subscribers.push(fn)
}
function dispatch(action) {
Object.keys(reducers).forEach(it => {
state = {
...state,
[it]: reducers[it].bind(null, state[it])(action)
}
})
subscribers.forEach(fn => fn(state))
}
const _vm = new Vue({
data() {
return {
$$game: dispatch({
type: initType,
})
}
},
})
const store = {
get state() {
return _vm._data.$$game
},
reducers,
dispatch,
subscribe
}
function applyMiddles(mds = []) {
mds.reduce((fn, _store) => fn(_store), store)
}
store.applyMiddles = applyMiddles
subscribe(() => {
_vm._data.$$game = state
})
return store
}
export const install = (_Vue) => {
Vue = _Vue
const version = Number(Vue.version.split('.')[0])
if (version >= 2) {
Vue.mixin({ beforeCreate: vuexInit })
} else {
const _init = Vue.prototype._init
Vue.prototype._init = function (options = {}) {
options.init = options.init
? [vuexInit].concat(options.init)
: vuexInit
_init.call(this, options)
}
}
function vuexInit () {
const options = this.$options
if (options.store) {
this.$store = typeof options.store === 'function'
? options.store()
: options.store
} else if (options.parent && options.parent.$store) {
this.$store = options.parent.$store
}
}
}