Vuex 状态管理

本文主要介绍关于复杂项目中的状态管理方案 Vuex 以及 Vuex 的使用,通过简单的购物车案例体验下使用Vuex来进行数据管理好处,以及自己来手写一个自己的 Vuex

Vue 组件间通信方式

组件内的状态管理流程

Vue 最核心的两个功能:数据驱动组件化

组件化开发的优点:

  • 更快的开发效率
  • 更好的可维护性

每个组件都有自己的状态(state)、视图(view)和行为(actions)等组成部分

  • state:数据可以称之为状态,每个组件内部都可以管理自己的内部状态
  • view:模板可以称之为视图,每个组件都有自己的视图,把状态绑定到视图上给用户
  • actions:用户与视图交互的时候可能会更改状态,当状态发生变化后会自动更新到视图,更改状态的部分可以称之为行为
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
new Vue({
// state
data () {
return {
count: 0
}
},
// view
template: `<div>{{ count }}</div>`,
// actions
methods: {
increment () {
this.count++
}
}
})

这里我们描述的是单个组件的状态管理,实际开发过程中可能多个组件都要共享状态,我们所说的状态管理就是通过状态集中管理和分发解决多个组件共享状态的问题。

状态管理包含以下几部分:

  • state:驱动应用的数据源
  • view:以声明方式将 state 映射到视图
  • actions:响应在 view 上的用户输入导致的状态变化

    vuex

    这里的箭头是数据的流向,此处数据的流向是单向的,State状态就是我们所说的数据,数据绑定到视图展示给用户,当用户和视图交互,通过Actions更改数据重新绑定到视图。

单向的数据流程非常清晰,但是多个组件共享数据时会破坏这种简单的结构,接下来我们来看一下组件之间的通信方式。

组件间通信方式

大多数场景下的组件都并不是独立存在的,而是相互协作共同构成了一个复杂的业务功能。在 Vue 中为不同的组件关系提供了不同的通信规则。

组件通信方式

父组件给子组件传值

父传子:Props Down

  • 父组件中给子组件通过相应属性传值
1
2
<!-- 通过属性,将值从父组件传给子组件 -->
<child title="My journey with Vue"></child>
  • 子组件中通过 props 接收数据
1
2
3
4
5
6
7
8
Vue.component('child', { 
// 接收父组件传给子组件的值
// props: ['title'],
props: { // 通过对象接收,可以设置数据的类型以及默认值...
title: String
},
template: '<h3>{{ title }}</h3>'
})

子组件给父组件传值

子传父:Event Up

  • 在子组件中使用 $emit 发布一个自定义事件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<template>
<button @click="handler">Enlarge text</button>
</template>

<script>
export default {
methods: {
handler () {
// 自定义事件 enlargeText
// this 当前子组件对象,即由子组件触发的自定义事件
this.$emit('enlargeText', 0.1)
}
}
}
</script>
  • 在父组件中,使用子组件时,使用 v-on 监听这个自定义事件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<template>
<!-- 给子组件注册自定义事件 enlargeText -->
<child :fontSize="hFontSize" v-on:enlargeText="enlargeText"></child>
</template>

<script>
export default {
methods: {
// 子组件把值传递给父组件
enlargeText (size) {
this.hFontSize += size
}
}
}
</script>

当在父级组件监听这个事件的时候,使用 $event (事件) 抛出一个值

1
2
<!-- $event 为触发自定义事件时,传递的值 -->
<child :fontSize="hFontSize" v-on:enlargeText="hFontSize += $event"></child>

不相关组件传值

非父子组件:Event Bus

  • 首先,使用一个非常简单的 Event Bus(创建一个公共的Vue实例作为事件总线/事件中心) 来解决这个问题:

    • eventbus.js :
    1
    2
    3
    // 创建一个公共的 Vue 实例
    import Vue from 'vue'
    export default new Vue()
  • 然后在需要通信的两端:

    • 使用 $on 订阅:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    <template>
    <div>
    <h1>Event Bus Sibling02</h1>
    <div>{{ msg }}</div>
    </div>
    </template>

    <script>
    import bus from './eventbus'
    export default {
    data () {
    return {
    msg: ''
    }
    },
    created () {
    bus.$on('numchange', (value) => {
    this.msg = `您选择了${value}件商品`
    })
    }
    }
    </script>
    • 使用 $emit 发布:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    <template>
    <div>
    <h1>Event Bus Sibling01</h1>
    <div class="number" @click="sub">-</div>
    <input type="text" style="width: 30px; text-align: center" :value="value">
    <div class="number" @click="add">+</div>
    </div>
    </template>

    <script>
    import bus from './eventbus'
    export default {
    props: {
    // 文本框默认显示的商品个数
    num: Number
    },
    // 因为props的值不建议直接修改,将props数据存储到value中
    created () {
    this.value = this.num
    },
    data () {
    return {
    value: -1
    }
    },
    methods: {
    sub () {
    if (this.value > 1) {
    this.value--
    bus.$emit('numchange', this.value)
    }
    },
    add () {
    this.value++
    bus.$emit('numchange', this.value)
    }
    }
    }
    </script>

其它常见方式

通过 ref 获取子组件

父组件直接访问子组件:通过 ref 获取子组件

  • ref 作用:
    • 在普通 HTML 标签上使用 ref,获取到的是 DOM
    • 在组件标签上使用 ref,获取到的是组件实例
  • 创建 child 组件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<template>
<input ref="input" type="text" >
</template>

<script>
export default {
methods: {
// 用来从父级组件聚焦输入框
focus () {
// 获取 input 标签,对应的 DOM 对象
this.$refs.input.focus()
}
}
}
</script>
  • 在使用子组件的时候,添加 ref 属性
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!-- 子组件 -->
<template>
<div>
<h1>ref Child</h1>
<input ref="input" type="text" v-model="value">
</div>
</template>

<script>
export default {
data () {
return {
value: ''
}
},
methods: {
// 用来从父级组件聚焦输入框
focus () {
this.$refs.input.focus()
}
}
}
</script>
  • 在父组件等渲染完毕后使用 $refs 访问
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!-- 父组件 -->
<template>
<div>
<h1>ref Parent</h1>
<child ref="c"></child>
</div>
</template>
<script>
import child from './04-Child'
export default {
components: {
child
},
mounted () {
// 等组件渲染完毕,获取子组件对象,操作子组件的方法和属性
this.$refs.c.focus()
this.$refs.c.value = 'hello input'
}
}
</script>

$refs只会在组件渲染完成之后生效,并且它们不是响应式的。这仅作为一个用于直接操作子组件的“逃生舱”——你应该避免在模板或计算属性中访问 $refs

当前组件树的根 Vue 实例,通过 vm.$root 获取

  • 类型:Vue instance
  • 特性:只读
  • 详细:

当前组件树的根 Vue 实例。如果当前实例没有父实例,此实例将会是其自己。

子组件直接访问父组件,通过 vm.$parent 获取父组件

  • 类型:Vue instance
  • 特性:只读
  • 详细:

父实例,如果当前实例有的话。

当前实例的直接子组件,通过 vm.$children 获取

  • 类型:Array
  • 特性:只读
  • 详细:

当前实例的直接子组件。需要注意 $children 并不保证顺序,也不是响应式的。如果你发现自己正在尝试使用 $children 来进行数据绑定,考虑使用一个数组配合 v-for 来生成子组件,并且使用 Array 作为真正的来源。

简易的状态管理方案

  • 如果多个组件之间要共享状态(数据),使用上面的方式虽然可以实现,但是比较麻烦,而且多个组件之间互相传值很难追踪数据的变化,如果出现问题很难定位问题。

  • 当遇到多个组件需要共享状态的时候,典型的场景:购物车。我们使用上述的方式都不合适,我们会遇到以下的问题:

    • 多个视图依赖同一状态
    • 来自不同视图的行为需要变更同一状态
  • 对于问题一,传参的方法对于多层嵌套的组件将会非常繁琐,并且对于兄弟组件间的状态传递无能为力。
  • 对于问题二,我们经常会采用父子组件直接引用或者通过事件来变更和同步状态的多份拷贝。以上的这些模式非常脆弱,通常会导致无法维护的代码。
  • 因此,我们为什么不把组件的的共享状态抽取出来(将来使用时保证其为响应式的),以一个全局单例模式来管理呢?在这种模式下,我们的组件树构成了一个巨大的“视图”,不管树在哪个位置,任何组件都能获取状态或者触发行为。
  • 我们可以把多个组件的状态,或者整个程序的状态放到一个集中的位置存储,并且可以检测到数据的更改。你可能已经想到了 Vuex 这里我们先以一种简单的方式来实现:

    • 首先创建一个共享的状态仓库 store 对象,这是集中式的状态管理,所有状态都在 store 中进行管理,且它为全局唯一的对象,任意的组件都可以导入 store 模块使用其中的状态,更改状态也是在该模块中实现的:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    // store.js
    export default {
    debug: true,
    // state 存储数据
    state: {
    user: {
    name: 'xiaomao',
    age: 18,
    sex: '男'
    }
    },
    // action 当视图和用户交互的时候,进行状态的更改
    setUserNameAction (name) {
    if (this.debug) {
    console.log('setUserNameAction triggered:', name)
    }
    this.state.user.name = name
    }
    }
    • 把共享的仓库 store 对象,存储到需要共享状态的组件 data 中
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    <!-- componentA.vue -->
    <template>
    <div>
    <h1>componentA</h1>
    user name: {{ sharedState.user.name }}
    <button @click="change">Change Info</button>
    </div>
    </template>

    <script>
    import store from './store'
    export default {
    methods: {
    // 点击按钮的时候通过 action 修改状态
    change () {
    store.setUserNameAction('componentA')
    }
    },
    data () {
    return {
    // 当前组件特有的自己的状态,存储到privateState
    privateState: {},
    // 把store中的state(共享的状态)存储到sharedState
    sharedState: store.state
    }
    }
    }
    </script>

    componentA 和 componentB 两个组件共享了 store 中的状态,并且和用户交互的时候还会更改状态中的 name 属性

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    <!-- componentB.vue -->
    <template>
    <div>
    <h1>componentB</h1>
    user name: {{ sharedState.user.name }}
    <button @click="change">Change Info</button>
    </div>
    </template>

    <script>
    import store from './store'
    export default {
    methods: {
    change () {
    store.setUserNameAction('componentB')
    }
    },
    data () {
    return {
    privateState: {},
    sharedState: store.state
    }
    }
    }
    </script>
    • 这里我们采用了集中式的状态管理,使用了全局唯一的对象 store 来存储状态,并且有一个共同点约定:组件不允许直接变更属于 store 对象的 State,而应执行 Action 来分发(dispatch)事件通知 store 去改变,这样最终的样子跟 Vuex 的结构就类似了。

    • 这样约定的好处是,我们能够记录所有 store 中发生的 State 变更,同时实现能做到记录变更、保存状态快照、历史回滚/时光旅行的先进的调试工具。

Vuex 核心概念

什么是 Vuex

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。Vuex 也集成到 Vue 的官方调试工具 devtools extension,提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。

  • Vuex 是专门为 Vue.js 设计的状态管理库
  • Vuex 采用集中式的方式存储需要共享的数据
  • 从使用角度,Vuex 就是一个 JavaScript 库
  • Vuex 的作用是进行状态管理,解决复杂组件通信,数据共享
  • Vuex 集成到了 devtools 中,提供了 time-travel 时光旅行历史回滚功能

什么情况下使用 Vuex

官方文档:

  • 非必要的情况不要使用 Vuex

Vuex 可以帮助我们管理共享状态,并附带了更多的概念和框架。这需要对短期和长期效益进行权衡。

  • 大型的单页应用程序
    • 多个视图依赖同一状态
    • 来自不同视图的行为需要变更同一状态

如果您不打算开发大型单页应用,使用 Vuex 可能是繁琐冗余的。确实是如此——如果您的应用够简单,您最好不要使用 Vuex。一个简单的 store模式 就足够您所需了。但是,如果您需要构建一个中大型单页应用,您很可能会考虑如何更好地在组件外部管理状态,Vuex 将会成为自然而然的选择。引用 Redux 的作者 Dan Abramov 的话说就是:Flux 架构就像眼镜:您自会知道什么时候需要它。

建议符合这种场景的业务使用 Vuex 来进行数据管理,例如非常典型的场景:购物车案例

注意:Vuex 不要滥用,不符合以上需求的业务不要使用,反而会让你的应用变得更麻烦。

Vuex核心概念

vuex核心概念

这张图展示了 Vuex 的核心概念,并且演示了整个工作流程:

  • 从State开始,State 是我们管理的全局状态

  • 把状态绑定到 Vue Components 组件(也就是视图上)渲染到用户界面展示给用户

  • 用户可以和视图交互(比如点击购买按钮支付的时候),此时 Dispatch 分发 Actions(此处不直接提交 Mutations 是因为 Actions 中可以做异步的操作,购买的时候要发送异步请求)

  • 当异步请求结束再通过提交 Mutations 记录状态的更改(Mutations必须是同步的,所有状态的更改都要通过Mutations,这样做的目的是为了追踪到所有状态的变化,阅读代码的时候更容易分析应用内部状态改变,还可以记录其改变实现高级的调试功能,比如 time-travel,历史回滚功能。)

Vuex 核心概念

  • Store:仓库,是使用Vuex应用程序的核心,每一个应用仅有一个Store。Store是一个容器,包含应用中的大部分状态,不能直接改变Store中的状态,要通过提交Mutation的方式
  • State:状态保存至Store中,因为Store是唯一的,因此状态也是唯一的,称为单一状态树。但是如果所有的状态都保存在State中,程序则难以维护,可以通过后续的模块来解决该问题。注意,这里的状态时响应式的
  • Getter:像是Vuex中的计算实现,方便从一个属性派生出其他的值。它内部可以对计算的结果进行缓存,只有当依赖的状态发生改变时才会重新计算
  • Mutation:状态的变化必须通过提交Mutation来完成
  • Action:和Mutation类似,不同的是Action可以进行异步操作,内部改变状态的时候都需要提交Mutation
  • Module:模块,由于使用单一状态树,应用的所有状态会集中到一个比较大的对象上来,当应用变得非常复杂时,Store对象就有可能变得非常臃肿。为了解决这个问题,Vuex允许我们将Store分割成模块每个模块拥有自己的State、Mutation、Action、Getter甚至是嵌套的子模块

基本结构

使用 Vue-cli 创建项目的时候,如果选择了 Vuex,会自动生成 Vuex 的基本结构:

Vuex 和 VueRputer 都是 Vue 的插件。插件内部把 Vuex 的 Store 注入到 Vue 的实例上,然后创建 Vuex 中的 Store 对象并且导出。

Store 构造函数接收 state、mutations、actions,modules,如果有需要还可以有 getters

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// store/index.js

import Vue from 'vue'
// 导入vuex
import Vuex from 'vuex'
// 注册vuex
Vue.use(Vuex)
// 导出store对象
export default new Vuex.Store({
state: {
},
mutations: {
},
actions: {
},
modules: {
}
})

创建 Vue 实例的时候传入 store 选项,这个 store 选项会被注入到 Vue 实例中,在组件中使用到的 this.$store 就是在这个位置注入的。

1
2
3
4
5
6
7
8
// main.js
import store from './store'
new Vue({
router,
// 注入到vue中
store,
render: h => h(App)
}).$mount('#app')

State

  • Vuex 使用单一状态树,集中存储所有的状态数据,响应式数据,用一个对象就包含了全部的应用层级状态。

    • 在 store/index.js 中,定义 state ,用来存储数据状态

      1
      2
      3
      4
      5
      6
      7
      export default new Vuex.Store({
      // 在仓库中设置的状态,在任何组件中都可以使用
      state: {
      count: 0,
      msg: 'Hello Vuex'
      }
      })

      组件中直接使用$store获取state中的值

      1
      2
      3
      4
      <template>
      <div> count:{{ $store.state.count }}</div>
      <div>msg: {{ $store.state.msg }}</div>
      </template>
  • 使用 mapState 函数 简化 State 在视图中的使用,mapState 函数 返回计算属性

  • mapState 函数 有两种使用的方式:

    • 接收数组参数

      1
      2
      3
      4
      5
      6
      7
      8
      // 该方法是 vuex 提供的,所以使用前要先导入 
      import { mapState } from 'vuex'

      // mapState 返回名称为 count 和 msg 的计算属性
      // 在模板中直接使用 count 和 msg
      computed: {
      ...mapState(['count', 'msg'])
      }
    • 接收对象参数

    • 若当前视图中已经存在 count 和 msg,如果使用上述方式的话会有命名冲突,解决的方式:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      // 该方法是 vuex 提供的,所以使用前要先导入 
      import { mapState } from 'vuex'

      // 通过传入对象,可以重命名返回的计算属性
      // 在模板中直接使用 num 和 message
      computed: {
      ...mapState({
      num: state => state.count,
      message: state => state.msg
      })
      }

      // 传入的对象的属性,是最终生成的计算属性的名称
      // 属性值,是映射的状态属性
      computed: {
      ...mapState({ num: 'count', message: 'msg' })
      }

Getter

  • Getter 就是 store 中的计算属性,当我们需要对数据做处理,再在视图中展示时,使用 Getter

    • 在 store/index.js 中,定义 getters,用来对数据进行处理
    1
    2
    3
    4
    5
    6
    7
    8
    9
      export default new Vuex.Store({
    getters: {
    // 参数:state,要处理的数据状态
    reverseMsg (state) {
    // 返回处理完毕的结果,跟计算属性一样
    return state.msg.split('').reverse().join('')
    }
    }
    })
    • 使用 mapGetters 函数 简化视图中的使用
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    import { mapGetters } from 'vuex'
    export default {
    computed: {
    ...mapGetter(['reverseMsg']),
    // 当存在相同变量名时,需要传入对象的形式,进行改名,
    // 属性值:新的变量名,属性值:映射的状态属性
    ...mapGetter({
    // 在模板中使用 reverse
    reverse: 'reverseMsg'
    })
    }
    }

Mutation

  • mutation 是更改 Vuex 的 store 中的状态 state 的唯一方法;
  • mutation 必须是同步操作的,保证在 mutation 中收集到全部的状态修改,方便在 devtools 中调试;
  • Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的事件类型 (type) 和 一个回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数;

    • 在 store/index.js 中,定义 mutations,定义更改状态 state 的方法
    1
    2
    3
    4
    5
    6
    7
    8
    export default new Vuex.Store({
    mutations: {
    // state 参数不需要手动传递
    increate (state, payload) {
    state.count += payload
    }
    }
    })
    • 模拟点击事件,增加 count
    1
    2
    3
    4
    <!-- Mutation 的调用要通过 commit,$store.commit() 提交 mutation  -->
    <!-- 参数1:increate 是 mutation 中方法的名字,相当于事件的名称 -->
    <!-- 参数2:2 是方法中除 state 外的其他参数 payload 的值,依次往后 -->
    <button @click="$store.commit('increate', 2)">Mutation</button>
    • 使用 mapMutations 函数 ,将 mutations 中的方法,映射到当前组件的 methods 中
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    import { mapMutations } from 'vuex'

    export default {
    methods: {
    // 把 this.increate() 映射为 this.$store.commit('increate')
    //...mapMutations(['increate'])
    //传对象解决重名的问题
    ...mapMutations({
    increateMut: 'increate'
    })
    }
    }
    • 使用 mapMutations 函数 简化视图中的使用
    1
    2
    <!-- state 参数不需要手动传递,3 代表 payload  -->
    <button @click="increate(3)">Mutation</button>
  • 使用 Mutation 改变状态的好处是,集中的一个位置对状态修改,不管在什么地方修改,都可以追踪到状态的修改。可以实现高级的 time-travel 调试功能。

需要注意的是:不要在 Mutations 中执行异步操作修改 state,否则调试工具无法正常地观测到状态的变化,如果需要,可以使用Aciton

Action

Action 类似于 mutation,不同在于:

  • Action 提交的是 mutation,而不是直接变更状态。也就是说,在执行完异步操作后,如果需要更改状态,则需要提交 mutation,进行 state 的修改。
  • Action 可以包含任意异步操作。

    • 在 store/index.js 中,定义 actions,利用 setTimeout 模拟异步操作

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      export default new Vuex.Store({
      actions: {
      // context 执行上下文
      // context 与 store 实例具有相同方法和属性
      // 注意:context 不是 store 的实例
      increateAsync (context, payload) {
      setTimeout(() => {
      context.commit('increate', payload)
      }, 2000)
      }
      }
      })

      Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。

    • 模拟点击事件,增加 count

      1
      2
      <!-- Action 的调用要通过 dispatch -->
      <button @click="$store.dispatch('increateAsync', 5)">Action</button>
    • 使用 mapActions 函数 ,将 actions 中的方法,映射到当前组件的 methods 中

      1
      2
      3
      4
      5
      6
      7
      8
      import { mapActions } from 'vuex'

      export default {
      methods: {
      // 把 this.increate() 映射为 this.$store.dispatch('increateAsync')
      ...mapActions(['increateAsync'])
      }
      }
    • 使用 mapActions 函数 简化视图中的使用

    1
    <button @click="increateAsync(6)">Action</button>

Module

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter,甚至是嵌套子模块。

案例演示

  • 创建 products 模块
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const state = {
products: [
{ id: 1, title: 'iPhone 11', price: 8000 },
{ id: 2, title: 'iPhone 12', price: 10000 }
]
}
const getters = {}
const mutations = {
setProducts (state, payload) {
state.products = payload
}
}
const actions = {}

export default {
state,
getters,
mutations,
actions
}
  • 在 store/index.js 中,注册模块,将 products 和 cart 模块挂载到 store.state 中
1
2
3
4
5
6
7
8
9
10
import products from './modules/products'
import cart from './modules/cart'

export default new Vuex.Store({
modules: {
// 会把模块的 mutation 记录到 store 的内部属性 _mutations 中
products,
cart
}
})
  • 模拟点击事件,增加 count ,提交 products 模块中的 mutation
1
2
3
4
5
<!-- 从全局命名空间的 store 中获取 -->
<!-- $store.state.模块名称.成员名 访问到模块中的成员 -->
products: {{ $store.state.products.products }} <br />
<!-- 通过 $store.commit() 直接提交 products 模块中的 mutation -->
<button @click="$store.commit('setProducts', [])">Mutation</button>
  • 默认情况下,模块内部的 action、mutation 和 getter 是注册在全局命名空间的——这样使得多个模块能够对同一 mutation 或 action 作出响应。

  • 通过添加 namespaced: true 的方式使其成为带命名空间的模块,使模块具有更高的封装度和复用性。

    • 当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名

      1
      2
      3
      export default {
      namespaced: true
      }
    • 使用 mapState 、 mapMutations 等,将 state 、mutations 等中的成员,映射到当前组件的 computed、methods中

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      import { mapState, mapMutations } from 'vuex'

      export default {
      computed: {
      // 参数1:模块名称 (命名空间),参数2:数组,映射模块中的state
      ...mapState('products', ['products'])
      },
      methods: {
      // 参数1:模块名称(命名空间),参数2:数组,映射模块中的 mutation
      ...mapMutations('products', ['setProducts'])
      }
      }

      这里可以清楚的看到映射的 State 和 Mutation 是从哪个模块中获取到的,不带命名空间的话就是从全局的store中获取的

    • 使用 mapState、mapMutations 等简化视图中的使用

      1
      2
      3
      <!-- 根据命名空间,从模块中获取 -->
      products: {{ products }} <br />
      <button @click="setProducts([])">Mutation</button>

strict 严格模式

所有的状态变更必须通过提交Mutation,但是这仅仅是一个约定。

如果你想的话,你可以在组件中随时获取到 $store.state.msg 对它进行修改,从语法层面这是没有问题的,但是这破坏了Vuex的约定。如果在组件中直接修改 state,devtools 无法跟踪到这次状态的修改。

开启严格模式后,如果你在组件中直接修改 state 状态,会抛出错误。

  • 开启严格模式,仅需在创建 store 的时候传入 strict: true
1
2
3
4
const store = new Vuex.Store({
// ...
strict: true
})
  • 测试
1
<button @click="$store.state.msg = 'Lagou'">strict</button>

在严格模式下,无论何时发生状态变更,只要此次变更不是由 mutation 函数引起的,就会抛出错误。这能保证所有的状态变更都能被调试工具跟踪到。

严格模式

开发环境与生产环境

不要在生产环境下启用严格模式!严格模式会深度监测状态树来检测不合规的状态变更——请确保在发布环境下关闭严格模式,以避免性能损失。

  • 类似于插件,我们可以让构建工具来处理这种情况,在开发环境中启用严格模式,在生产中关闭。
1
2
3
4
const store = new Vuex.Store({
// ...
strict: process.env.NODE_ENV !== 'production'
})

模拟实现 Vuex

案例代码:my-vuex

基本结构

自己模拟实现一个 Vuex 实现同样的功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<template>
<div id="app">
<h1>Vuex - Demo</h1>
count:{{ $store.state.count }} <br>
msg: {{ $store.state.msg }}

<h2>Getter</h2>
reverseMsg: {{ $store.getters.reverseMsg }}

<h2>Mutation</h2>
<button @click="$store.commit('increate', 2)">Mutation</button>

<h2>Action</h2>
<button @click="$store.dispatch('increateAsync', 5)">Action</button>
</div>
</template>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
state: {
count: 0,
msg: 'Hello World'
},
getters: {
reverseMsg (state) {
return state.msg.split('').reverse().join('')
}
},
mutations: {
increate (state, payload) {
state.count += payload
}
},
actions: {
increateAsync (context, payload) {
setTimeout(() => {
context.commit('increate', payload)
}, 2000)
}
}
})

实现思路

  • 实现 install 方法
    • Vuex 是 Vue 的一个插件,所以和模拟 VueRouter 类似,先实现 Vue 插件约定的 install 方法
  • 实现 Store 类
    • 实现构造函数,接收 options
    • state 的响应化处理
    • getter 的实现
    • commit、dispatch 方法

install

  • src/myvuex/index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 存储 install 中获取到的 vue构造函数
let _Vue = null
function install (Vue) {
_Vue = Vue
// 获取 vue 实例 从而拿到选项中的 store
Vue.mixin({
// 当创建Vue的根实例,会把store注入到所有vue实例
beforeCreate () {
// this 指 Vue 实例
// $options 指 创建 Vue 实例时,传入的参数
// 如果是组件实例,没有store选项
if (this.$options.store) {
// 将 store 注入到所有的 Vue 实例中
_Vue.prototype.$store = this.$options.store
}
}
})
}

Store 类

  • src/myvuex/index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Store {
constructor (options) {
const {
// 防止用户没有传入,设置默认值
state = {},
getters = {},
mutations = {},
actions = {}
} = options

// 将 state 设置成响应式的
this.state = _Vue.Observable(state)
/**
* 此处不直接 this.getters = getters,是因为下面的代码中要 getters 中的 key
* 如果这么写的话,会导致 this.getters 和 getters 指向同一个对象
* 当访问 getters 的 key 的时候,实际上就是访问 this.getters 的 key,会触发 key 属性的 getter
* 会产生死递归
*/
// 创建一个没有原型的对象
this.getters = Object.create(null)
Object.keys(getters).forEach(key => {
// 把对应的key注册到this.getters对象中
Object.defineProperty(this.getters, key, {
get: () => getters[key](state)
})
})
// 私有属性
this._mutations = mutations
this._actions = actions
}

// 提交 mutation
commit (type, payload) {
this._mutations[type](this.state, payload)
}

// 分发 actions
dispatch (type, payload) {
// 简单模拟,传入this即可
this._actions[type](this, payload)
}
}

// 导出模块
export default {
Store,
install
}

使用自己实现的 Vuex

  • src/store/index.js 中修改导入 Vuex 的路径,测试
1
2
3
import Vuex from '../myvuex'
// 注册插件
Vue.use(Vuex)

参考

vuex
购物车案例