let _Vue = null
class Store{
constructor(options){
let vm = new Vue({
data: {
state:options.state
}
})
this.state = vm.state
this.mutations = {}
let mutations = options.mutations||{}
Object.keys(mutations).forEach(key=>{
this.mutations[key] = params=>{
mutations[key].call(this, this.state, params)
}
})
this.actions = {}
let actions = options.actions||{}
Object.keys(actions).forEach(key=>{
this.actions[key] = params=>{
actions[key].call(this, this, params)
}
})
this.getters = {}
let getters = options.getters||{}
Object.keys(getters).forEach(key=>{
Object.defineProperty(this.getters, key, {
get: ()=>{
return getters[key].call(this, this.state)
}
})
})
}
commit = (key, parmas)=>{
this.mutations[key](params)
}
dispath = (type, payload)=>{
this.actions[type](payload)
}
}
export const mapState = args=>{
let obj = {}
args.forEach(item=>{
obj[item] = function(){
return this.$store.state[item]
}
})
return obj
}
export const mapGetters = args=>{
let obj = {}
args.forEach(item=>{
obj[item]= function (){
return this.$store.getters[item]
}
})
return obj
}
export const mapMutations = args =>{
let obj = {}
args.forEach(item=>{
obj[item]= function (params){
return this.$store.commit(item, params)
}
})
return obj
}
export const mapActions =args=>{
const obj = {}
args.forEach(item=>{
obj[item]= function (payload){
return this.$store.dispatch(item, payload)
}
})
return obj
}
function install(Vue){
_Vue = Vue
_Vue.minxin({
beforeCreate() {
if(this.$options.store){
_Vue.prototype.$store = this.$options.store
}else if(this.$parent&&this.$parent.$store){
this.$store = this.$parent.$store
}
},
})
}
export default {
Store,
install
}
总结:
1.作为vue状态管理的插件,vuex采用了单一状态树。每个应用将仅仅包含一个 store 实例。单一状态树让我们能够直接地定位任一特定的状态片段,在调试的过程中也能轻易地取得整个当前应用状态的快照
2.每个.vue的文件中都能访问到vuex中的数据
3.实现vuex的思路:
a.作为vue的插件 ,需要提供一个install方法, 由于要满足所有vue组件中均能访问, 在install中传入的当前应用的实例上(vue的插件机制默认会将当前的应用实例传给该参数 install(Vue))采用 mixin的方法在beforeCreate中将$store注入,子组件会继承父组件上的store
b.将vuex获得的配置中的state/mutation/action/getter挂在在store的实例上,并注意使用call进行指针的绑定和参数的传递
c.定义commit方法用来接受一个事件名称及额外的参数,并调用store实例上的mutation中对应事件名的处理函数,dispath同理
d.定义一些快捷的store方法mapState等 思路是通过便利对应的keys数组 ,获取或执行对应的store实例上维护的数据或方法,并组装成{key:结果的键值对}放在一个obj中返回