time: 2019.6.7
author: heyunjiang
最近在使用 vuex ,这里也需要总结一下 vuex 的相关知识点
通过在入口文件中创建一个 store 对象
Vue.use(Vuex)
const store = new Vuex.Store(storeConfig);
new Vue({
store
})
这里是让每个非动态生成的组件,都可以使用到一个公用的 store 对象,可以访问 store 对象的属性和方法;
如果是动态生成的组件,即通过 new Vue()
生成一个组件,需要在配置中传入 store 对象
关键 api
mapState 为什么要在计算属性中添加呢?
因为它的参数对象写法,更像是 computed 对象写法;mapState 内部是会去遍历对象并且执行它,返回的是一个结果对象,跟 computed 有什么关系?是因为它的效果同 computed 一样,在 state 数据变化之后,更新它对应的依赖源对象
为什么我们能通过 $store 访问到全局状态数据呢?
在 Vuex 插件中,执行了如下操作
export function install (_Vue) {
Vue = _Vue
applyMixin(Vue)
}
export default function (Vue) {
Vue.mixin({ beforeCreate: vuexInit })
function vuexInit () {
const options = this.$options
// store injection
if (options.store) {
this.$store = typeof options.store === 'function'
? options.store()
: options.store
} else if (options.parent && options.parent.$store) {
this.$store = options.parent.$store
}
}
}
源码解读:
options.store || options.store()
来加载总结归纳:
export class Store {
constructor (options = {}) {
this._modules = new ModuleCollection(options)
const state = this._modules.root.state
resetStoreVM(this, state)
}
get state () {
return this._vm._data.$$state
}
function resetStoreVM (store, state, hot) {
const oldVm = store._vm
// 1. 将 getters 转换为 computed
store.getters = {}
store._makeLocalGettersCache = Object.create(null)
const wrappedGetters = store._wrappedGetters
const computed = {}
forEachValue(wrappedGetters, (fn, key) => {
computed[key] = partial(fn, store)
Object.defineProperty(store.getters, key, {
get: () => store._vm[key],
enumerable: true // for local getters
})
})
const silent = Vue.config.silent
Vue.config.silent = true
// 2. 将 state 挂载到一个新的 vue 实例 data 上,实现响应式数据
store._vm = new Vue({
data: {
$$state: state
},
computed
})
Vue.config.silent = silent
}
}
总结归纳: