Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

bigcatLiu/sourceCodeAnalysis

Folders and files

NameName
Last commit message
Last commit date

Latest commit

History

4 Commits

Repository files navigation

读Vuex源码--基于3.0.1 esm版

Vue技术栈作为当今前端的核心技能之一,应该熟练掌握,不仅应该知其然,更应该知其所以然。以下部分为个人读vuex源码心得,主要分为三个部分,一个部分是从整体看其原理,一个是局部每个函数的实现过程分析,还有一部分是补充文档中未提及的部分

[toc]

源代码

vuex.esm.js v3.0.1

从整体看

整个存储体系是由module节点组成的一棵树,而 ModuleCollection则是这棵树的管理者 ,这是一个典型的组合模式。 当通过moduleCollection进行register,update,unRegister时,ModuleCollection是不进行具体的操作的,他只是把这些任务派发给具体的module,通过module自身的 addChild , update , removeChild进行实际的操作。此外,ModuleCollection还提供了对这棵树路径操作的办法,比如将从根节点到指定的子节点的路径以字符串的方式表达的getNamespace(path);比如根据指定路径获取module节点的 get( path ) 方法。

而每个module提供两部分功能,一类是操作自身,一类是管理子节点。操作自身的方法主要对应着module自身的_rawModule进行操作;管理子节点,主要对应着module的_children进行操作。

  • 操作自身的有 : update , forEachGetter , forEachMutation , forEachAction。
  • 管理子节点的有 : addChild , removeChild , getChild , forEachChild

当调用 new Vuex.Store( options ), 主要过程是:

  • 通过 `this._modules = new ModuleCollection(options)` 构造这棵树。
    
  • 通过 `installModule(this, state, [], this._modules.root)` 将这颗树的相关信息进行处理并存储到我们store实例的各个属性中,当对store实例的各种操作,实质上都是在用这棵树提供的信息功能进行相应的处理。
    

局部

补充

关于mapState

当其第二个参数(第一个参数是namespace,可以没有)为对象时,该对象的键对应的值是函数时,除了获取namespace指定的state,还会获取对应的getters 源码中有:

 return typeof val === 'function'
 ? val.call(this, state, getters)
 : state[val]

因此调用时可以:

 mapState({
 field : function( state , getters ){}
 })

关于mapMutations

当其第二个参数(第一个参数是namespace,可以没有)为对象时,该对象的键对应的值可以是函数,该函数第一个参数会是namespace指向的commit 源码中:

 return typeof val === 'function'
 ? val.apply(this, [commit].concat(args))
 : commit.apply(this.$store, [val].concat(args))

因此调用时可以:

 mapMutations({
 field : function( commit , payload ){
 //其他代码...
 commit('type',payload);
 //...
 }
 })

关于mapActions

当其第二个参数(第一个参数是namespace,可以没有)为对象时,该对象的键对应的值可以是函数,该函数第一个参数会是namespace指向的dispatch 源码中:

 return typeof val === 'function'
 ? val.apply(this, [dispatch].concat(args))
 : dispatch.apply(this.$store, [val].concat(args))

因此调用时可以:

 ...mapActions({
 asyncAdd( dispatch , payload){
 dispatch('type',payload)
 .then(function( data ){
 console.log( '数据已经递交:' , data )
 })
 }
 })
 国安信徒
 2018年04月05日

About

读一些源码的分析,感想

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

AltStyle によって変換されたページ (->オリジナル) /