自定义状态管理器store js文件
状态管理器原理:用的是三方库
Vue.use(Vuex)
use 自定义插件,去调用install的方法
export default new Vuex.Store({})
Store用于存储数据以及提供数据访问接口
let Vue;
//数据存储 class指es6类
class Store{
//构造器
//在构造器中new一个vue,把外部的state拿进来
constructor(options){
this.vm = new Vue({
data:{
state:options.state
}
})
//getter 获取数据
let getters = options.getters
this.getters = {}
//遍历外面对象里所有的key
Object.keys(getters).forEach(getterName=>{
//在对象中动态的添加属性
//在this.getters对象中定义getterName属性
Object.defineProperty(this.getters,getterName,{
//添加查询方法
get:()=>{
//查询外部getters属性内的getterName方法并传参
return getters[getterName](this.state)
}
})
})
//actions 修改数据
let actions = options.actions
this.actions = {}
Object.keys(actions).forEach(actionName=>{
this.actions[actionName] = (payload)=>{
//调用外部方法
actions[actionName](this,payload)
}
})
//mutations
let mutations = options.mutations
this.mutation = {}
Object.keys(mutations).forEach(mutationName=>{
this.mutations[matationName] = (payload)=>{
mutations[mutationName](this.state,payload)
}
})
}
dispatch(type,payload){
this.actions[type](payload)
}
//调mutations
commit = (type,payload)=>{
this.mutations[type](payload)
}
//访问的方法
get state(){
return this.vm.state;
}
}
//插件需要 需要在所有的组建中添加$store对象
//染发所有的组建中可以使用this.$store.commit()
//所有组件都有$store
const install = (v)=>{
console.log(v)//vue函数对象
Vue = v;
//给每个组件添加$store属性
Vue.mixin({
//在组件初始化之前
beforeCreated(){
//组件名字
//$options指vue传过来的配置项:main.js中的new Vue
console.log(this.$options.name)
//只有根节点有store
if(this.$options && this.$options.store){
//在根节点加上$store
this.$store = this.$options.store
}else{
//子节点
this.$store = this.$parent && this.$parent.$store
}
}
})
}
export default {install,Store}