简易版vuex的实现

vuex是我们在vue项目开发中经常用到的工具,那么今天就来实现一个简易版的vuex哈

什么是vuex?

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

v2-f330e46f1a97cfe60b8914802688083b_r.jpg

vuex的基本使用

    // store.js
    import Vue from "vue"
    import Vuex from "vuex"
    Vue.use(Vuex) 
    export default new Vuex.Store({
      state: {
        text: "Hello Vuex"
      },
      getters: {},
      mutations: {},
      actions: {},
      modules: {}
    )}

复制代码

简易版vuex的实现

let Vue

// 创建一个 store 类
class Store {
    constructor(options) {
        // 1. 保存传入的选项
        this._mutations = options.mutaitions
        this._actions = options.actions
        
        // 2. 对传入的 state 选项做响应式处理
        this._vm = new Vue({
            data() {
                return {
                    $$state: options.state
                }
            }
        })
        
        // 绑定上下文,确保是store实例
        this.commit = this.commit.bind(this)
        this.dispatch = this.dispatch.bind(this)
    }
    
    // 当用户读取store中的 state 时,实际上走的时这儿
    get state () {
        return this._vm.$$state
    }
    // 当用户尝试修改 state 中的数据时提示报错,只允许用户提交commit来进行数据修改
    set state (v) {
        console.error('please use replaceState to reset state');
    }
    
    // 实现 commit 方法
    commit(type, payload) {
        const entry = this._mutations[type] // 根据传入的字段匹配相应的mutation
        if (!entry) {
            console.error('unknown mutation')
        }
        entry(this.state, payload) // 执行该 mutation 并传入 state 和 commit 提交的 payload
    }
    
    // 实现 dispatch 方法
    dispatch (type, payload) {
        const entry = this._actions[type] // 根据传入的字段匹配相应的 action
        if (!entry) {
            console.error('unknown action')
        }
        entry(this, payload) // 分发该 dispatch 并传入 store实例
    }
    
}

// 实现 install 方法
function install(_Vue) {
    Vue = _Vue
    
    // 在Vue.use()执行 install 方法时,将Store实例挂在到Vue
    Vue.mixin({
        beforeCreate () {
            // 这里的 this 是指 vue 实例
            if (this.$options.store) {
                Vue.prototype.$store = this.$options.store
            }
        }
    })
}

// 对外暴露 Stroe 类和 install 方法
export default { Stroe, install }
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享