Vuex

Vuex 介绍

每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的**状态(state)**。Vuex 和单纯的全局对象有以下两点不同:

  1. Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
  2. 不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交**(commit)mutation**。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。

我的理解: Vuex 相当于一个扩展板的bus中介.起步虽相似,但功能更丰富.

Vuex 之 store

起步: 安装,引入,use,创建状态仓库.在 Vue 实例中注入(把 store 写进去).一条龙服务.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//创建仓库格式
var store = new Vuex.Store({
state: {
//定义你的状态
XXX: xxx
},
mutations: {
//在此处定义状态改变的方法
increase(state){
state.num ++
}
decrease(state){
state.num --
}
},
actions: {
//actions中传递的不再是state,而是context
increaseAction(context){
//actions中只能对mutations中的方法进行操作
context.commit('increase')
}
}
})

mutations 改变状态:

直接通过this.$store.state.XXX拿到状态

在 methods 中.定义一个函数通过this.$store.commit('xxx')方法触发状态变更

actions 改变状态:

通过this.$store.dispatch(xxx)调用

二者区别:

  1. 传入参数不同,mutations 传入state.actions 传入context
  2. 调用方式不同,前者this.$store.commit('xxx').后者this.$store.dispatch(xxx)
  3. 函数要求不同.mutations 中只能有同步操作,actions 中可以有异步操作.

getters

有时需要对 mutations 处理后的 state 进行处理.

可以当做 vuex 的计算属性(computed).

1
2
3
4
5
6
7
getters: {
getNum(state){
//因为要处理state,自然传入state
return state.num > 0 ? state.num : 0
//这里是防止一直减出现负数进行的处理
}
}

获取状态也就改为

1
2
3
4
5
6
7
//在组件中
computed: {
getCount(){
//return this.$store.state.num
return this.$store.getters.getNum
}
}

Vuex 状态管理流程

view–>actions–>mutations–>state–>view

新增

VueX 中

state相当于data

getter相当于computed

mutation相当于methods

action是异步的mutation

module模块将上述进行封装分块

mapState 和 mapGetters

mapState辅助函数仅仅是将 store 中的getter映射到局部计算属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
...Vuex.mapState(['firstName', 'lastName'])
//相当于
firstName(){
return this.$store.state.firstName
},
lastName(){
return this.$store.state.lastName
}

..Vuex.mapGetters(['fullName'])
//相当于
fullName(){
return this.$store.getters.fullName
}

store.commit('xxFirstName', 'jirengu')

提交 mutation 中 xxFirstName 的方法。

第一个参数是 state 中有的,后添加的 jirengu 是载荷payload

提交载荷(payload)

store.commit传入额外参数,即mutation的载荷

1
2
3
4
5
6
7
8
mutations:{
increment (state, payload){
state.count += payload.amount
}
}
store.commit('increment', {
amount: 10
})

actions 中传入第一个参数是context,第二个是payload

触发 action

1
store.dispatch("increment");

moudle(模块化)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}

const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}

const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态