Vue框架(三)-Vuex原理篇

71 阅读1分钟

Vuex原理篇

1. 设计思路

  • 统一状态存储 store,state为响应式的
  • 可预测变更,唯一修改途径 store.commit()

2. 创建Store实例

1. 插件方法

 store.install = function(app) {
     const store = this
     
     // 全局注册$store
     app.config.globalProperties.$store = store
 }

2. state为响应式的

// vue引入reactive
const store = {
    _state: reactive(options.state())
}

3. 不能随意修改state

Object.defineProperty(store, 'state', {
    get state() {
        return this._state
    },
    set state(v) {
        console.error('please use replaceState() to reset state')
    }
})

4. 唯一修改途径 commit()

const store = {
    ...
    _mutations: options.mutations,
}

fuction commit(type, payload) {
    const entry = this._mutations[type]
    if(!entry) {
        console.error(`unknown mutation type: ${type}`)
        return
    }
    entry.call(this.state, this.state, payload)
}

store.commit = commit.bind(store)

5. 异步处理 dispatch()

const store = {
    ...
    _actions: options.actions,
}

function dispatch(type, payload) {
    const entry = this._actions[type]
    if(!entry) {
        console.error(`unknown dispatch type: ${type}`)
        return
    }
   return entry.call(this, this, payload)
}
store.dispatch = commit.dispatch(store)

5. 计算属性 getters

store.getters = {}

// 遍历getters
Object.keys(options.getters).forEach((key) => {
    // 缓存计算结果, vue引入computed
    const result = computed(() => {
        const getter = options.getters[key]
        if(getter) {
            return getter.call(store, store.state)
        } else {
            console.error('unknown getter type:' + type)
            return ''
        }
    })
    
    // 只读限制
    Object.defineProperty(store.getters, key, {
        get() {
            return result
        }
    })
})