Centralized State Management for Vue.js.
先抛出问题
vuex核心功能如下
核心功能在store.js
,根据注释阅读便于理解。
最后我们回过来看文章开始提出的5个问题。
答:
Vue.use(Vuex)
方法执行的是install方法,它实现了Vue实例对象的init方法封装和注入,使传入的store对象被设置到Vue上下文环境的$store中。因此在Vue Component任意地方都能够通过this.$store
访问到该store。
答:在store构造方法中有makeLocalContext方法,所有module都会有一个local context,根据配置时的path进行匹配。所以执行如
dispatch('submitOrder', payload)
这类action时,默认的拿到都是module的local state,如果要访问最外层或者是其他module的state,只能从rootState按照path路径逐步进行访问。
答:store初始化时,所有配置的action和mutation以及getters均被封装过。在执行如
dispatch('submitOrder', payload)
的时候,actions中type为submitOrder的所有处理方法都是被封装后的,其第一个参数为当前的store对象,所以能够获取到{ dispatch, commit, state, rootState }
等数据。
答:Vuex中修改state的唯一渠道就是执行
commit('xx', payload)
方法,其底层通过执行this._withCommit(fn)
设置_committing标志变量为true,然后才能修改state,修改完毕还需要还原_committing变量。外部修改虽然能够直接修改state,但是并没有修改_committing标志位,所以只要watch一下state,state change时判断是否_committing值为true,即可判断修改的合法性。
答:devtoolPlugin中提供了此功能。因为dev模式下所有的state change都会被记录下来,'时空穿梭' 功能其实就是将当前的state替换为记录中某个时刻的state状态,利用
store.replaceState(targetState)
方法将执行this._vm.state = state
实现。
Running the examples:
$ npm install
$ npm run dev # serve examples at localhost:8080