经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » Vue.js » 查看文章
手写 Vuex4 源码 - xingba-coder
来源:cnblogs  作者:xingba-coder  时间:2023/8/9 9:15:00  对本文有异议

本文首发于掘金,未经许可禁止转载

Vuex4 是 Vue 的状态管理工具,Vuex 和单纯的全局对象有以下两点不同:

  1. Vuex 的状态存储是响应式的
  2. 不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地 提交 (commit) mutation

本文手写部分分为八个部分,基本包含了 Vuex 的功能。

  • 实现获取state并响应式修改state
  • 实现getters
  • 实现 commit 和 dispatch
  • 注册模块
  • 注册模块上的 getters,mutations,actions 到 store 上
  • 命名空间
  • 严格模式
  • 插件模式

准备工作

创建名字叫 vuex_source 的工程

  1. vue-cli3 create vuex_source

上面命令和使用 vue create vuex_source 创建项目是等价的,我电脑安装了 vue-cli2vue-cli3,在 vue-cli3里面修改了 cmd 文件,所以可以用上面命令。

image.png

选择 Vuex,使用空格选择或取消选择

image.png

image.png

启动项目如果如下图报错

image.png

可以试试输入命令

  1. $env:NODE_OPTIONS="--openssl-legacy-provider"

image.png

基本使用

使用 createStore 创建一个 store

  1. import { createStore } from 'vuex'
  2. export default createStore({
  3. strict:true,
  4. state: {
  5. count:1
  6. },
  7. getters: {
  8. double(state){
  9. return state.count * 2
  10. }
  11. },
  12. mutations: {
  13. mutationsAdd(state,preload){
  14. state.count += preload
  15. }
  16. },
  17. actions:{
  18. actionAdd({commit},preload){
  19. setTimeout(() => {
  20. commit('mutationsAdd',preload)
  21. }, 1000);
  22. }
  23. }
  24. })

main.js 中引入

  1. import { createApp } from 'vue'
  2. import App from './App.vue'
  3. import store from './store'
  4. createApp(App).use(store).mount('#app')

在 app.vue 中使用 store

  1. <template>
  2. 数量:{{count}} {{$store.state.count}}
  3. <br>
  4. double:{{double}} {{$store.getters.double}}
  5. <br>
  6. <!-- 严格模式下会报错 -->
  7. <button @click="$store.state.count++">错误增加</button>
  8. <br>
  9. <button @click="mutationsAdd">正确增加mutation</button>
  10. <br>
  11. <button @click="actionAdd">正确增加 action</button>
  12. </template>
  13. <script>
  14. import { computed } from "vue";
  15. import { useStore } from "vuex";
  16. export default {
  17. name: 'App',
  18. setup(){
  19. const store = useStore()
  20. const mutationsAdd = () =>{
  21. store.commit('mutationsAdd',1)
  22. }
  23. const actionAdd = () =>{
  24. store.dispatch('actionAdd',1)
  25. }
  26. return {
  27. // 来自官网解释:从 Vue 3.0 开始,getter 的结果不再像计算属性一样会被缓存起来。这是一个已知的问题,将会在 3.1 版本中修复。
  28. // 使用 count:store.state.count 返回的话,模板中的 {{count}}并不是响应式的,这里必须加上 computed 此时响应式的
  29. count:computed(() => store.state.count),
  30. double:computed(() => store.getters.double),
  31. mutationsAdd,
  32. actionAdd,
  33. }
  34. }
  35. }
  36. </script>

vuex.gif

编写源码

实现获取state并响应式修改state

修改 App.vue 的引用,@/vuex 是需要编写的源码的文件夹

  1. import { useStore } from "@/vuex"; // 之前是import { useStore } from "vuex";

修改 store 的引用

  1. import { createStore } from '@/vuex'

在 src 目录下创建 vuex文件夹,里面添加 index.js

image.png

在 index.js 中添加 createStore 和 useStore 函数,createStore 用来创建 store,useStore 供页面调用

  1. // vuex/index.js
  2. class Store{
  3. constructor(options){
  4. }
  5. }
  6. // 创建 store,多例模式
  7. export function createStore(options){
  8. return new Store(options)
  9. }
  10. // 使用 store
  11. export function useStore(){}

createStore 创建出的store,在main.js 中 调用 use 方法

  1. createApp(App).use(store)

use 会调用 store 的 install 方法,将 store 安装到 Vue 上,所以 Store 类中还需要添加 install 方法

  1. const storeKey = 'store' // 默认一个 store 名
  2. class Store{
  3. constructor(options){
  4. }
  5. install(app,name){
  6. // app 是vue3暴露的对象
  7. // 在根组件上绑定了 store,子组件要用到 store
  8. // 根组件就需要 provide 出去,子组件 inject 接收
  9. app.provide(name || storeKey,this)
  10. }
  11. }
  12. // 创建 store
  13. export function createStore(options){
  14. return new Store(options)
  15. }
  16. // 使用 store
  17. export function useStore(name){
  18. // inject 去找父组件的 provide 的东西
  19. return inject(name!==undefined?name:storeKey)
  20. }

此时在 App.vue 中打印的就是一个空对象

  1. // App.vue
  2. const store = useStore()
  3. console.log(store);

image.png

在 Store 类中绑定传进来的 state

  1. constructor(options){
  2. this.state = options.state
  3. }

打印就是

image.png

App.vue 中添加如下模板

  1. <template>
  2. 数量:{{count}} // 正常打印 1
  3. 数量:{{$store.state.count}} // 报错了
  4. <br>
  5. <button @click="$store.state.count++">错误增加</button>
  6. </template>
  7. <script>
  8. import { computed } from "vue";
  9. import { useStore } from "@/vuex";
  10. export default {
  11. name: 'App',
  12. setup(){
  13. const store = useStore()
  14. console.log(store);
  15. return {
  16. count:computed(() => store.state.count)
  17. }
  18. }
  19. }
  20. </script>

上面模板中的 {{$store.state.count}} 会报错,是因为 $store 没有绑定到 this 上。vue3 中绑定到 this 可以用 app.config.globalProperties[属性名]

  1. // createApp(App).use(store,name)会调用store的install方法
  2. install(app,name){
  3. // app 是vue3暴露的对象
  4. app.provide(name || storeKey,this)
  5. app.config.globalProperties.$store = this
  6. }
  7. }

$store 绑定到 this 后就不会报错了

但此时点击 错误增加 的按钮没有任何效果,

vuex2.gif

因为此时 store.state 并不是响应式的,需要增加响应式效果,vue3 为复杂数据提供了 reactive

  1. class Store{
  2. constructor(options){
  3. // 这里给options.state加了一层,用 data 包裹是为了重新赋值的时候可以直接 this._store.data = 。。。 ,而不用再使用 reactive
  4. this._store = reactive({data:options.state})
  5. this.state = this._store.data
  6. }
  7. // createApp(App).use(store,name)会调用store的install方法
  8. install(app,name){
  9. // app 是vue3暴露的对象
  10. app.provide(name || storeKey,this)
  11. app.config.globalProperties.$store = this
  12. }
  13. }

这时候 错误增加 的按钮就有效果了

vuex3.gif

实现getters

模板中是使用 getters 是以属性的方式:

  1. // App.vue
  2. 数量:{{count}}
  3. 数量:{{$store.state.count}}
  4. <br>
  5. double:{{double}}
  6. double:{{$store.getters.double}}
  7. <br>
  8. <button @click="$store.state.count++">错误增加</button>

在 store.js 中定义的getters 是由一个大对象里面包含多个函数组成

  1. getters: {
  2. double(state){
  3. return state.count * 2
  4. }
  5. },

在 store 中 double 是函数,返回的 state.count * 2的结果。 在模板中使用的是 $store.getters.double ,这个 double 是 getters 上的一个属性。所以这里需要进行转换

  1. const forEachValue = function(obj,fn){
  2. return Object.keys(obj).forEach((key) =>{
  3. fn(obj[key],key)
  4. })
  5. }
  6. class Store{
  7. constructor(options){
  8. this._store = reactive({data:options.state})
  9. this.state = this._store.data
  10. this.getters = Object.create(null)
  11. forEachValue(options.getters,(fn,key) => {
  12. // 当模板解析 $store.getters.double 时,
  13. // 就去执行 options.getters里面对应属性的函数,并将函数结果赋予该属性
  14. Object.defineProperty(this.getters,key,{
  15. // vue3.2之前的vuex中不能使用计算属性 computed,导致每次访问的时候都会执行函数引发潜在性能问题
  16. // vue3.2修复了这个bug
  17. get:() => {
  18. return fn(this.state)
  19. }
  20. })
  21. })
  22. }
  23. // createApp(App).use(store,name)会调用store的install方法
  24. install(app,name){
  25. // app 是vue3暴露的对象
  26. app.provide(name || storeKey,this)
  27. app.config.globalProperties.$store = this
  28. }
  29. }

forEachValue 函数接收一个对象参数 obj 和一个处理函数参数 fn;里面会遍历对象,循环调用 fn;

这里遍历 options.getters ,响应式注册到 this.getters 上,这样当模板解析 $store.getters.double 时,就会执行对应的 fn

点击错误增加按钮,改变 $store.state.count 的值进而导致 getters 值的变化

vuex4.gif

实现 commit 和 dispatch

commit 和 dispatch 在组件中是这样使用的:

  1. <template>
  2. <button @click="mutationsAdd">正确增加 mutation</button>
  3. <br>
  4. <button @click="actionAdd">正确增加 action</button>
  5. </template>
  6. <script>
  7. import { useStore } from "@/vuex";
  8. export default {
  9. name: 'App',
  10. setup(){
  11. const store = useStore()
  12. const mutationsAdd = () =>{
  13. store.commit('mutationsAdd',1)
  14. }
  15. const actionAdd = () =>{
  16. store.dispatch('actionAdd',1)
  17. }
  18. return {
  19. mutationsAdd,
  20. actionAdd,
  21. }
  22. }
  23. }
  24. </script>

store.js 中定义的是这样的:

  1. mutations: {
  2. mutationsAdd(state,preload){
  3. state.count += preload
  4. }
  5. },
  6. actions:{
  7. // 异步调用
  8. actionAdd({commit},preload){
  9. setTimeout(() => {
  10. commit('mutationsAdd',preload)
  11. }, 1000);
  12. }
  13. }

调用 mutation : store.commit(mutation类型,参数)

调用 action : store.dispatch(action类型,参数)

在 Store 类中实现 commit:

  1. class Store{
  2. constructor(options){
  3. // 将 store.js 中定义的 mutations 传进来
  4. this._mutations = options.mutations
  5. this.commit = function(name,preload){
  6. if(this._mutations[name]!==undefined){
  7. // 根据传进来的类型,调用对应的方法
  8. this._mutations[name](this.state,preload)
  9. }
  10. }
  11. }
  12. }

效果如下,数量每次增加 1

vuex5.gif

在 Store 类中实现 dispatch:

  1. class Store{
  2. constructor(options){
  3. // 将 store.js 中定义的 actions 传进来
  4. this._actions = options.actions
  5. this.dispatch = function(name,preload){
  6. if(this._actions[name]!==undefined){
  7. // 根据传进来的类型,调用对应的方法
  8. let fn = this
  9. // dispatch 进来调用的是 actionAdd({commit},preload)
  10. this._actions[name].apply(fn,[fn].concat(preload))
  11. }
  12. }
  13. }
  14. }

dispatch 调用的参数是({commit},preload),所以这里传进去需要是 (this,preload)

看看效果:

vuex6.gif

这里报了错,由 dispatch 触发 actions 正常,但 actions 触发 对应的 mutations 出错了,显示 this 是 undefined。那么这里就要修改下之前的 commit 实现了,先用一个变量将 Store 类实例的 this 保存起来

  1. class Store{
  2. constructor(options){
  3. // 这里创建一个 store 变量保存 this 是方便之后嵌套函数里面访问当前 this
  4. let store = this
  5. this._mutations = options.mutations
  6. this.commit = function(name,preload){
  7. if(store._mutations[name]!==undefined){
  8. store._mutations[name](store.state,preload)
  9. }
  10. }
  11. this._actions = options.actions
  12. this.dispatch = function(name,preload){
  13. if(store._actions[name]!==undefined){
  14. store._actions[name].apply(store,[store].concat(preload))
  15. }
  16. }
  17. }
  18. }

这样就可以了

vuex7.gif

注册模块

平常使用中定义 modules 如下

  1. // store/index.js
  2. import { createStore } from 'vuex'
  3. export default createStore({
  4. // strict: true,
  5. state: {
  6. count: 1
  7. },
  8. // ...
  9. modules: {
  10. aCount: {
  11. state: {
  12. count: 1
  13. },
  14. modules: {
  15. cCount: {
  16. state: {
  17. count: 1
  18. },
  19. },
  20. }
  21. },
  22. bCount: {
  23. state: {
  24. count: 1
  25. },
  26. }
  27. }
  28. })

组件中使用

  1. // App.vue
  2. <template>
  3. 数量(根模块):{{$store.state.count}} <button @click="$store.state.count++">增加</button>
  4. <br>
  5. 数量(aCount模块):{{$store.state.aCount.count}} <button @click="$store.state.aCount.count++">增加</button>
  6. <br>
  7. 数量(cCount模块):{{$store.state.aCount.cCount.count}} <button @click="$store.state.aCount.cCount.count++">增加</button>
  8. <br>
  9. </template>

vuex8.gif

先实现将用户定义的多个 modules 进行格式化,创造父子关系

用户传进来的数据

image.png

格式化后的数据

image.png

上面的每个 modules 下的数据格式如下

  1. this._raw = modules // 保存不做处理的源数据
  2. this.state = modules.state // 保存状态
  3. this.children = {} // 创建子对象
  • _raw 保存不做处理的源数据
  • state 保存状态
  • children 保存子模块

比如 bCount

  1. // 格式化前
  2. bCount:{
  3. state: {
  4. count: 1
  5. },
  6. }
  7. // 格式化后
  8. bCount: {
  9. _raw: bModule, // 这里放的是格式化前的数据
  10. state: bModule.state,
  11. children: {}
  12. },

所以这里定义一个类 moduleCollection,专门用来收集模块,将用户写的嵌套 modules 格式化,创造父子关系

  1. class Store {
  2. constructor(options) {
  3. const store = this
  4. // 收集模块,将用户写的嵌套modules格式化,创造父子关系
  5. store._modules = new moduleCollection(options)
  6. console.log(store._modules)
  7. }
  8. }

在 moduleCollection类中定义 register 方法处理数据,定义 this.root 保存处理过后的数据

  1. class moduleCollection{
  2. constructor(rootModule){
  3. // root 存储格式化的数据,方便后续安装到 store.state 上
  4. this.root = null
  5. this.register(rootModule,[])
  6. }
  7. register(rootModule,path){
  8. }
  9. }

register 方法接受两个参数

一个表示当前处理的模块数据 rootModule ,一个表示当前处理的是谁的模块数据 path

path之所以用数组表示,是因为后面建造父子关系时,使用path可以进行关联

比如 path 是空数组,则表示处理的是根模块的数据,是 [a] 则表示处理的是 a 模块,是[a,c] 则表示处理的是 c 模块的数据,并且,c模块的数据要加到 a 模块的 children 中。

对于 register 方法:

首先将用户定义的 store 格式化赋值给 this.root,这里可以抽象出一个类,因为每个模块的格式都是 _raw,state,children

  1. class Module{
  2. constructor(modules){
  3. this._raw = modules
  4. this.state = modules.state
  5. this.children = {}
  6. }
  7. getChild(key){
  8. return this.children[key]
  9. }
  10. addChild(key,module){
  11. this.children[key] = module
  12. }
  13. }
  14. class moduleCollection{
  15. register(rootModule,path){
  16. const newModule = new Module(rootModule)
  17. if(path.length===0){
  18. this.root = newModule
  19. }
  20. }
  21. }

然后判断 最外层的 store 中也就是根模块还有没有子模块,如果有,继续递归格式化子模块数据

  1. // 如果根模块下还有子模块,则继续递归注册
  2. if(rootModule.modules){
  3. Object.keys(rootModule.modules).forEach((key) =>{
  4. this.register(rootModule.modules[key],path.concat(key))
  5. })
  6. }

用户定义的 store 中,根模块下定义了子模块,子模块里面分别是 aCount 和 bCount,所以执行到上面代码时, key 就是 aCount,bCount

rootModule.modules[key] 是他们对应的模块数据

当执行到 aCount 模块时,此时的 path 是[a],代表处理 aCount 的数据,这时我们要在根模块上添加 aCount,如果 path 是 [aCount,cCount],则需要在 aCount 模块上添加 cCount 模块,所以这里需要定义一个寻找父模块的方法。

使用 path.slice(0,-1) 得到父模块的 key,默认是根模块

  1. const parent = path.slice(0,-1).reduce((modules,current) =>{
  2. return modules.getChild(current)
  3. },this.root)

参数 modules 代表上一次执行结果,current代表当前元素,初始传入根模块

这里如果 path 是 [a], 传入给 reduce 时是 [] ,那么返回的就是 this.root

path 是[a,c],传入给reduce 时是 [a], 当执行module.getChild(current) 实际上就是 this.root.getChild(a)

找到父模块后,给父模块的 children 添加 modules

  1. parent.addChild(path[path.length-1],newModule)

moduleCollection 类完整代码:

  1. class moduleCollection{
  2. constructor(rootModule){
  3. // root 存储格式化的数据,方便后续安装到 store.state 上
  4. this.root = null
  5. this.register(rootModule,[])
  6. }
  7. register(rootModule,path){
  8. // 注册模块,每个模块的格式都是
  9. // _raw: rootModule,
  10. // state: rootModule.state,
  11. // children: {}
  12. // 所以给传进来的模块都格式化一下
  13. const newModule = new Module(rootModule)
  14. // 注册根模块
  15. if(path.length===0){
  16. this.root = newModule
  17. }else{
  18. // 注册子模块,将子模块添加到对应的父模块,通过 path路径可以知道对应的父模块
  19. const parent = path.slice(0,-1).reduce((modules,current) =>{
  20. return modules.getChild(current)
  21. },this.root)
  22. parent.addChild(path[path.length-1],newModule)
  23. }
  24. // 如果根模块下还有子模块,则继续递归注册
  25. if(rootModule.modules){
  26. Object.keys(rootModule.modules).forEach((key) =>{
  27. this.register(rootModule.modules[key],path.concat(key))
  28. })
  29. }
  30. }
  31. }

得到格式化数据后,需要将各个模块的 state 安装在 store.state 上,以便之后调用:$store.state.aCount.cCount.count$store.state安装后的样子应该是:

  1. state:{
  2. count:1,
  3. aCount:{
  4. count:1,
  5. cCount:{
  6. count:1
  7. }
  8. },
  9. bCount:{
  10. count:1
  11. }
  12. }

创建一个 installModules 函数

  1. function installModules(store,modules,path){}
  2. class Store {
  3. constructor(options) {
  4. const store = this
  5. store._modules = new moduleCollection(options)
  6. console.log(store._modules)
  7. installModules(store,store._modules.root,[])
  8. console.log(store.state)
  9. }
  10. }

store 是当前 Store 类的实例对象,模块安装的地方

modules 是要安装的模块

path 对应父子关系

installModules 方法和 register 方法类似

  1. function installModules(store,modules,path){
  2. if(path.length===0){
  3. store.state = modules.state
  4. }else{
  5. const parent = path.slice(0,-1).reduce((result,current) =>{
  6. return result[current]
  7. },store.state)
  8. parent[path[path.length-1]] = modules.state
  9. }
  10. if(modules.children){
  11. Object.keys(modules.children).forEach((key) =>{
  12. installModules(store,modules.children[key],path.concat(key))
  13. })
  14. }
  15. }

这样也就得到了一个完整的 state

image.png

在组件中引用也能正确显示了

image.png

image.png

注册模块上的 getters,mutations,actions 到 store 上

  1. class Store {
  2. constructor(options) {
  3. const store = this
  4. // 收集模块,将用户写的嵌套modules格式化,创造父子关系
  5. store._modules = new moduleCollection(options)
  6. // 定义私有变量存放对应的 getters,actions,mutations
  7. store._getters = Object.create(null)
  8. store._mutations = Object.create(null)
  9. store._actions = Object.create(null)
  10. installModules(store,store._modules.root,[])
  11. }
  12. }

同样也是在 installModules 方法里面进行存放操作

在格式化模块时,已经将每个模块定义成这样的数据格式:

  1. this._raw = modules
  2. this.state = modules.state
  3. this.children = {}

_raw 存放的就是源数据,没有被格式化的数据。

所以,取得模块上的 getters 就是 modules._raw.getters;

取得模块上的 mutations 就是 modules._raw.mutations;

取得模块上的 actions 就是 modules._raw.actions;

遍历 modules._raw.getters ,安装到 store._getters 上。这里需要注意的是

getters的参数是 state,这个 state 本来是 modules._raw.state,但 _raw.state没有响应式,而后面store.state 是响应式的,需要根据 path 取得store.state里面对应的 state

  1. function getCurrentState(state,path){
  2. return path.reduce((result,current) =>{
  3. return result[current]
  4. },state)
  5. }
  6. function installModules(store,modules,path){
  7. ···
  8. ···
  9. if(modules._raw.getters){
  10. forEachValue(modules._raw.getters,(getters,key) =>{
  11. store._getters[key] = () =>{
  12. // 这里的参数不能是 modules._raw.state,没有响应式
  13. // 而后面 store.state 会是响应式的,需要根据 path 取得store.state里面对应的 state
  14. return getters(getCurrentState(store.state,path))
  15. }
  16. })
  17. }
  18. ···
  19. ···
  20. }

注册 mutations

  1. if(modules._raw.mutations){
  2. forEachValue(modules._raw.mutations,(mutations,key) =>{
  3. if(!store._mutations[key]){
  4. store._mutations[key] = []
  5. }
  6. store._mutations[key].push((preload) =>{ // store.commit(key,preload)
  7. mutations.call(store,getCurrentState(store.state,path),preload)
  8. })
  9. })
  10. }

在模块里面,可能有多个同名的 mutations,所以这里可能有多个同名 key,需要用数组包装起来

注册 actions

  1. if(modules._raw.actions){
  2. forEachValue(modules._raw.actions,(actions,key) =>{
  3. if(!store._actions[key]){
  4. store._actions[key] = []
  5. }
  6. store._actions[key].push((preload) =>{
  7. // store.dispatch({commit},preload)
  8. // actions执行后返回的是promise
  9. let res = actions.call(store,store,preload)
  10. if(!isPromise(res)){
  11. return Promise.resolve(res)
  12. }
  13. return res
  14. })
  15. })
  16. }

和 mutations 一样,也可能会有多个重名的 actions。区别是 actions 执行完后返回的是一个 promise

命名空间

命名空间的用法,添加 namespaced:true

  1. // store.js
  2. aCount: {
  3. namespaced:true,
  4. state: {
  5. count: 1
  6. },
  7. mutations: {
  8. mutationsAdd(state, preload) {
  9. state.count += preload
  10. }
  11. },
  12. modules: {
  13. cCount: {
  14. namespaced:true,
  15. state: {
  16. count: 1
  17. },
  18. mutations: {
  19. mutationsAdd(state, preload) {
  20. state.count += preload
  21. }
  22. },
  23. },
  24. }
  25. }

页面中就可以使用 $store.commit('aCount/mutationsAdd',1) 调用 aCount 下的 mutationsAdd

$store.commit('aCount/cCount/mutationsAdd',1) 调用 cCount 下的 mutationsAdd

在安装模块的时候,通过检测模块是否定义 namespaced 为 true,来给安装的模块的 actions,mutations 添加命名空间前缀

  1. function getNameSpace(modules,path){
  2. let root = modules.root
  3. // 传入的是 根模块
  4. // 当 path 是[],返回空字符串
  5. // 2、当 path 是 [aCount] ,根据path,取得根模块下的对应的 aCount , modules.getChild(aCount)
  6. // 然后判断 aCount 模块下是否定义namespaced,有则返回 aCount/
  7. // 当 path 是 [aCount,cCount] ,重复2,然后根据步骤2 取得的子模块,再往下找子模块cCount,
  8. // 然后判断 cCount 模块下是否定义namespaced,有则返回 aCount/cCount/
  9. // [] => '' [aCount] => 'aCount/' [aCount,cCount] => 'aCount/cCount'
  10. return path.reduce((module,current) =>{
  11. root = root.children[current]
  12. return root.namespaced?(module+current+'/'):''
  13. },'')
  14. }
  15. function installModules(store,modules,path,root){
  16. ···
  17. // 所以这里先根据path取得设置了 namespaced 的模块名字,拼接后注册到 mutations,actions的名字上
  18. const namespace = getNameSpace(root,path)
  19. console.log(namespace)
  20. if(modules._raw.mutations){
  21. forEachValue(modules._raw.mutations,(mutations,key) =>{
  22. if(!store._mutations[namespace + key]){
  23. store._mutations[namespace + key] = []
  24. }
  25. store._mutations[namespace + key].push((preload) =>{ // store.commit(key,preload)
  26. mutations.call(store,getCurrentState(store.state,path),preload)
  27. })
  28. })
  29. }
  30. }

在 getNameSpace 方法中,传入的参数 path 表示的是有父子关系的模块名组成的数组,通过 path 找到对应的模块,判断是否定义 namespaced 为 true。最终返回命名空间字符串

严格模式

要设置严格模式,在根节点上指定 strict:true 即可。

  1. const store = createStore({
  2. // ...
  3. strict: true
  4. })

设置了严格模式,没有通过 mutations 改变状态都会弹出一个报错信息(即通过 $store.state.count++ 直接改变状态)

并且官方建议不要在发布环境下启用严格模式

那么这里可以创建一个变量 isCommiting ,用来判断是否通过 mutations 改变状态,只要是执行了 mutations 方法的都去改变 isCommiting。

  1. store.commit = (type,preload) =>{
  2. this.withCommit(() =>{
  3. if(store._mutations[type]){
  4. store._mutations[type].forEach((fn) =>{
  5. fn(preload)
  6. })
  7. }
  8. })
  9. }
  1. withCommit(fn){
  2. this.isCommiting = true
  3. fn()
  4. this.isCommiting = false
  5. }

上面执行 mutations 之前,isCommiting 为 true,此时只需要知道,当状态变化的时候 isCommiting 不为 true,则提示报错。

这里每个数据状态变化都需要知道 isCommiting 的值,所以需要深度监听整个状态。深度监听会带来一定性能损耗,所以严格模式不建议在生产环境使用。

  1. if(store.strict){
  2. watch(() =>store._store.data,() =>{
  3. console.assert(store.isCommiting,'do not mutate vuex store state outside mutation handlers.')
  4. },{deep:true,flush:'sync'})
  5. }

效果如下:

  1. 数量(根模块):{{$store.state.count}}
  2. <button @click="$store.commit('mutationsAdd',1)">增加</button>
  3. <button @click="$store.state.count++">错误增加</button>

vuex9.gif

插件模式

Vuex 的插件实际上是一个函数,store 作为这个函数的唯一参数。定义插件即在 createStore 中定义 plugins 选项,选项是数组格式,可包含多个插件函数。这些插件函数会在创建 store 时依次执行

  1. const plugins1 = (store) => {
  2. // 当 store 初始化后调用
  3. store.subscribe((mutation, state) => {
  4. // 每次 mutation 之后调用
  5. // mutation 的格式为 { type, payload }
  6. })
  7. }
  8. const store = createStore({
  9. // ...
  10. strict: true,
  11. plugins:[plugins1],
  12. })

在插件中可以调用 subscribe 方法,参数是当前调用的 mutation 和调用 mutation 后的 state ,此时的 state 是最新的。并且 subscribe 中的函数都是在每次 mutation 之后调用。

根据这些,来实现 subscribe 方法

  1. class Store {
  2. constructor(options) {
  3. const store = this
  4. // ...
  5. store._subscribe = []
  6. store.subscribe = (fn) =>{
  7. store._subscribe.push(fn)
  8. }
  9. const plugins = options.plugins
  10. plugins.forEach(fn => {
  11. fn(store)
  12. });
  13. }

定义 _subscribe 私有变量数组,用来存储插件中 subscribe 的函数。如果定义了 plugins 选项,那么依次执行选项中的插件函数。

  1. store.commit = (type,preload) =>{
  2. this.withCommit(() =>{
  3. if(store._mutations[type]){
  4. store._mutations[type].forEach((fn) =>{
  5. fn(preload)
  6. })
  7. store._subscribe.forEach(fn => {
  8. fn({type:type,preload:preload},store.state)
  9. });
  10. }
  11. })
  12. }

在调用完 mutation 后,循环调用 _subscribe 的函数。这样每个函数中的 state 参数都是最新的

现在来实现一个持久化存储的插件,将状态存储在 sessionStorage 中,页面刷新后,从 sessionStorage 中取出并替换为最新状态。

  1. const customPlugin = (store) =>{
  2. const local = sessionStorage.getItem('vuexState')
  3. if(local){
  4. store.replaceState(JSON.parse(local))
  5. }
  6. store.subscribe((mutation,state) =>{
  7. sessionStorage.setItem('vuexState',JSON.stringify(state))
  8. })
  9. }

在 store.subscribe 参数函数中,每次调用 mutation 后,将状态存储在 sessionStorage 中。store.replaceState 则是一个替换状态的方法。

  1. replaceState(newState){
  2. this.withCommit(() =>{
  3. this._store.data = newState
  4. })
  5. }

效果如下:
image

总结

Vuex 在项目中用了很久,只知其然不知其所以然,故研究学习并实现出来。

从理解思路到手写出来,然后将实现过程记录下来就有了这篇文章,这个过程断断续续持续了大概一个月,项目和文章基本都是利用下班时间写的,确实挺累的,不过实现出来后往回看,还是学到很多东西,还挺欣慰的;文章有不足的地方还请各位大佬指正;

原文链接:https://www.cnblogs.com/zsxblog/p/17615611.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号