自定义状态管理器store js文件

自定义状态管理器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}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值