1.前言
使用过Vue框架的小伙伴们都应该接触过Vuex,Vuex是一个专门为Vue.js应用程序开发的状态管理模式。本篇博客我们主要是通过学习Vuex源码,弄清楚以下两个问题:
- Vuex通过什么方式提供响应式数据?
- $Store是如何挂载到实例this中?
2.Vuex通过什么方式提供响应式数据?
Vuex的两大核心State和Getters都是响应式的,即当state或getter的某一个状态改变时,它是能驱动视图发生相应的改变。
下面我们阅读部分源码(resetStoreVM()
方法):
function resetStoreVM (store, state, hot) {
/* 存放之前的vm对象 */
const oldVm = store._vm
store.getters = {
}
store._makeLocalGettersCache = Object.create(null)
const wrappedGetters = store._wrappedGetters
const computed = {
}
/*
通过Object.defineProperty为每一个getter方法设置get方法,比如获取
this.$store.getters.test的时候获取的是store._vm.test,也就是Vue
对象的computed属性
*/
/*
将所有的Getters存放到computed对象中,然后在下面的new Vue实例中,将其注册为computed
*/
forEachValue(wrappedGetters, (fn, key) => {
computed[key]