手写Vuex-简单实现

在这里插入图片描述

开门见山
本篇文章主要简单实现vuex,希望可以帮助到大家
代码演示
//用于保存vue实例
let _Vue = null
class Store {
    //options传入的选项
    constructor(options) {
        //对象的解构赋值如果没有值的话,就是用默认值
        const { state = {}, getters = {}, actions = {}, mutations = {} } = options;
        //state设置成响应式数据
        this.state = _Vue.observable(state);
        // 把this.getters初始化对象,对象具有一些方法,
        //这些方法都需要接收state参数,并且最后都有返回值,一般情况都是对state
        //进行处理,把处理的结果返回,这些方法都是用来获取值,当访问getter成员的时候
        //才会获取值,所以这些方法可以通过 Object.defineProperty转换成getter对象
        //中的get访问器,通过下面的这种方法对象更干净 
        this.getters = Object.create(null);
        //对getters进行遍历
        Object.key(getters).forEach(key => {
            //对this.getters每一个属性进行遍历,把每一个key注册到this.getters中
            Object.defineProperty(this.getters, key, {
                //返回key在getter中获取到的方法
                get: () => getters[key](state),
            })
        })

        //存储私有属性 下划线表示私有
        this._mutations = mutations;
        this._actions = actions;
    }

    //commit 有两个参数 type是mutation的key,payload是传入的参数

    commit(type, payload) {

        //调用保存的_mutations其中的方法,state是要操作的数据

        //payload是传入的参数

        this._mutations[type](this.state, payload);
    }

    //dispatch 有两个参数 type是mutation的key,payload是传入的参数

    dispatch(type, payload) {
        //dispatch 有两个参数this是_actions的key,payload是传入的参数
        this._actions[type](this, payload);
    }
}

function install(Vue) {
    //保存vue实例
    _Vue = Vue;
    //使用Vue混合机制
    _Vue.mixin({
        beforeCreate() {
            //逻辑判断是否有this.$options.store这个方法
            if (this.$options.store) {
                //在vue原型上注册$store方法
                _Vue.prototype.$store = this.$options.store
            }
        }
    })
}

export default { Store, install }

谢谢观看,如有不足,敬请指教

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值