支持vuex中的mapActions,mapMutations辅助函数,也可以在bindStore时添加到页面中,页面卸载时最好调佣 removeStore.remove() 来删除不需要更新的页面对象
页面中使用
或者
组件中使用
也可以这样
//初始化state值
let state = {
}
//更新state方法
let mutations = {
}
//公共方法
let actions = {
}
let stateProxy;
const Store = (options = {}) => {
if(options.state) state = options.state
if(options.state) mutations = options.mutations
if(options.state) actions = options.actions
//创建Proxy
stateProxy = new Proxy(state, {
get(target, property) {
return target[property]
},
set(target, property, value) {
pageArrays.forEach(item => {
const newData = {}
//判断该页面是否需要更新property
if (item.arr.includes(property)) {
newData[property] = value
}
item.self.setData(newData)
})
return Reflect.set(target, property, value)
}
})
return {
state,
commit: commitFun,
dispatch: dispatchFun,
}
}
//以下为主要代码(原理)
// Actions commit方法
export const commitFun = (str, params) => {
return mutations[str](stateProxy, params)
}
// Actions dispatch方法
export const dispatchFun = (str, params) => {
return actions[str]({
state,
commit: commitFun,
dispatch: dispatchFun
}, params)
}
//存放页面对象数组
const pageArrays = []
//创建数组索引
let id = 1;
//删除卸载的页面和组件
class RemovePageItem {
ids = null;
constructor(ids) {
this.ids = ids
}
remove() {
pageArrays.some((item, index, arr) => {
if (item.id === this.ids) {
arr.splice(index, 1)
return true
}
})
}
}
//绑定页面并初始化所需state
export const bindStore = (self, useState = [], useMutations = [], useActions = []) => {
id++
const newData = {}
useState.forEach(item => {
newData[item] = (state[item] || state[item] === 0) ? state[item] : ''
})
useMutations.forEach(item => {
self[item] = (params) => mutations[item](stateProxy, params)
})
useActions.forEach(item => {
self[item] = (params) => actions[item]({
state,
commit: commitFun,
dispatch: dispatchFun
}, params)
})
self.setData(newData)
pageArrays.push({
self,
id,
arr: useState
})
return new RemovePageItem(id)
}
//绑定更新state方法
export const mapMutations = (arr = []) => {
const List = {}
arr.forEach(item => {
List[item] = (params) => mutations[item](stateProxy, params)
})
return List
}
export const mapActions = (arr = []) => {
const List = {}
arr.forEach(item => {
List[item] = params => actions[item]({
state,
commit: commitFun,
dispatch: dispatchFun
}, params)
})
return List
}
const _default = {
...Store()
}
export default _default