开篇废话:想必每一个使用过vue技术栈进行开发的同学都知道vuex是一个全局状态管理库,其使用方法非常简单。作为一名开发人员我们要知其然,也要知其所以然,但是阅读源码却是一块非常难啃的骨头,看着看着就容易陷入从入门到放弃的过程。为了那些想看源码又不知如何下手的同学,我现在用几十行代码来详细讲解如何实现vuex核心
简单需求分析
- 回顾下vuex的初始化方式
Vue.use(Vuex); const store = new Vuex.Store({xxxxx}); const app = new Vue({store: store}) - 从使用方式得知,vuex要对外暴露一个Store类和一个install方法。
说明:install方法是vue规定插件必须提供的初始化方式。 - 定义一个state属性保存所有状态, 这个state是响应式
- 定义commit方法,触发mutations改变state状态值
- 定义dispatch方法,支持异步方式触发mutations该白state状态值
撸代码
- 创建
vuex.js 文件,定义Store类和install方法
class Store {
constructor(options) {
this.state=options.state
this._mutations = options.mutations
this._actions = options.actions
}
}
function install(_Vue){
}
export default { Store, install }
- 将vuex实例挂在到vue实例上
在vue实例中可以通过this.$store 访问vuex实例,这一步是通过install方法将vuex实例挂载到Vue原型上实现的Vue.prototype.$store = store ,这里我们会遇到第一个难题,在install方法中store实例还没有生成,如何才能拿到store实例呢?
此时可以想到Vue.mixin全局混入,在beforeCreate 中拿到vuex实例
function install(_Vue) {
_Vue.mixin({
beforeCreate() {
if (this.$options.store) {
Vue.prototype.$store = this.$options.store
}
}
})
}
- 将state设置成响应式
借助install方法传递进来Vue,构造一个新的vue实例将state设置成响应式
let Vue;
class Store {
constructor(options) {
this.state=new Vue({
data: options.state
})
}
}
function install(_Vue) {
Vue=_Vue
}
export default { Store, install }
虽然已经将state设置成了响应式,但是用户可能直接修改state,导致状态丢失产生悲剧,为了避免此事的发生, 我们可以隐藏state,然后借助存储器get / set函数拦截state的存储行为
let Vue;
class Store {
constructor(options) {
this._vm=new Vue({
data: options.state
})
}
get state(){
return this._vm._data
}
set state(){
console.error('请不要直接修改state')
}
}
- 定义commit方法,触发mutation更改state
commit = (type, payload) => {
const mutationType = this._mutations[type];
if (!mutationType) {
console.log(mutationType + "找不到");
}
mutationType(this.state, payload);
}
- 定义dispatch方法,支持异步的方式触发mutation,需要注意的是actions中的方法第一个参数是一个上下文对象,所以我们需要将this传递出去
dispatch = (type, payload) => {
const actionType = this._actions[type];
if (!actionType) {
console.log(actionType + "方法未定义");
}
actionType(this, payload);
};
至此一个极简的vuex已经实现了啦! 收工! 喂!三点几了,做卵啊做,写饮茶先啦! 
|