Yapei Li

专注于前端领域

0%

Vuex使用

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式

解决问题:

1、多个视图依赖于同一状态。
2、来自不同视图的行为需要变更同一状态。

工作原理图

组件内store.dispatch(‘actionsName’)一个 actions -> actionscontext.commit(‘mutationName’)一个mutations ->mutations内 直接改变state

不使用actions(不包含异步操作):组件内store.commit(‘mutationName’)一个mutations ->mutations内 直接改变state

Alt text

安装

1
2
3
4
5
6
npm install vuex --save

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

兼容性

Vuex 依赖 Promise。如果你支持的浏览器并没有实现 Promise (比如 IE),那么你可以使用一个 polyfill 的库,例如 es6-promise

然后在 使用 Vuex 前面引入

1
2
3
4
npm install es6-promise --save

import 'es6-promise/auto'
Vue.use(Vuex)

与全局变量的区别

1、Vuex 的状态存储是响应式的

Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到更新。

2、不能直接改变 store 中的状态

改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation,这样使得我们可以方便地跟踪每一个状态的变化。

规律

1、statemapState)、 gettermapGetters) 对应 computed计算属性
2、mutationsmapMutations) 、 actionsmapActions)对应methods
3、state是普通对象(json

getter每一项是: (属性名:属性值) 属性值为一个有返回值的函数

mutationsactions每一项都是一个函数(可以使用es6 的函数缩写xxx(state) {xxx})

4、getter函数

接受state作为第一个参数

接受其他getter作为第二个参数

通过让 Getter函数返回一个函数,来实现给 getter 传参

5、mutations函数

接受 state 作为第一个参数

接收payload (实参、有效荷载)作为第二个参数

6、actions函数

context作为第一个参数,调用context.commit提交一个mutation,或者通过context.statecontext.getters来获取 stategetters

payload (实参、有效荷载)作为第二个参数

7、语法糖第一个参数是可选的,可以是一个命名空间字符串
8、语法糖第二个参数一般传入json,每一个属性名对应的属性值只能是普通函数、箭头函数、字符串

8.1、使用常规函数才能使用 this 获取所在组件的状态

8.2、使用箭头函数不能使用 this 获取所在组件的状态,可使代码更简练接收state作为第一个参数获取到store的所有数据

8.3、使用字符串, countAlias: 'count'countAlias相当于给count起的别名;'count'相当于state => state.count

8.4、语法糖第二个参数的每一项,可以是属性名:属性值, 也可以是一个有返回值的函数 xxx(state) {return xxx}

9、语法糖第二个参数也可以是一个数组:当映射的计算属性的名称state 的子节点名称相同
10、除了语法糖引入mutationsactions直接调用以外,mutations对应context.commit('xxx')store.commit('xxx')actions对应store.dispatch('xxx')

简单的 使用

如果在模块化构建系统中,请确保在开头调用了 Vue.use(Vuex)

通过 store.state 来获取状态对象

通过 store.commit 方法触发mutations进行状态变更

1
2
3
4
5
6
7
8
9
10
11
12
13
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
}
}
store.commit('increment')
console.log(store.state.count) // -> 1

state (状态、数据)

因为store中的state是响应式的所以利用 computed计算属性进行读取state

子组件能通过 this.$store访问到store

在模块化的构建系统中,从根组件“注入”到每一个子组件中(需调用 Vue.use(Vuex)之后将store挂载到vue上),子组件能通过 this.$store 访问到

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
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex)
var store=new Vuex.Store({
state:{
count:1
}
})

//根组件引入store
const app = new Vue({
el: '#app',
// 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
store,
components: { Counter }
})

//子组件this.$store
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return this.$store.state.count
}
}
}

mapState辅助函数(语法糖)必须return

当使用普通函数与箭头函数时接收state作为第一个参数

为了能够使用 this 获取组件局部状态,必须使用常规函数

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
//计算属性只从vuex继承
import { mapState } from 'vuex'
computed: mapState({
// 箭头函数可使代码更简练
count: state => state.count,

// 传字符串参数 'count' 等同于 `state => state.count`
countAlias: 'count',

// 为了能够使用 `this` 获取组件局部状态,必须使用常规函数
countPlusLocalState (state) {
return state.count + this.localCount
}
})

//对象展开运算符
import { mapState } from 'vuex'
computed: {
localComputed () { /* ... */ },
// 使用对象展开运算符将此对象混入到外部对象中
...mapState({
// ...
})
}

//当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。
computed: mapState([
// 映射 this.count 为 store.state.count
'count'
])

getter

1、从 store 中的 state 中派生出的一些状态,获取并处理state中的数据以生成新的数据

2、一般都是通过getter获取state中的数据(不管数据是否需要处理)

3、通过store.getters 对象以属性的形式访问getter中的选项store.getters.doneTodos

Getter函数接受state作为第一个参数(数据来源)

1
2
3
4
5
6
7
8
9
10
11
12
13
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
}
})

Getter函数接受其他 getter 作为第二个参数,用来访问其他getter选项

1
2
3
4
5
6
getters: {
// ...
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
}
}

通过让 Getter函数返回一个函数,来实现给 getter 传参

1
2
3
4
5
6
7
8
getters: {
// ...
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
}

store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

在子组件的computed中通过this.$store.getters获取getter中的属性

1
2
3
4
5
computed: {
doneTodosCount () {
return this.$store.getters.doneTodosCount
}
}

mapGetters 辅助函数

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

1
2
3
4
5
6
7
8
9
10
11
12
13
import { mapGetters } from 'vuex'

export default {
// ...
computed: {
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}

如果你想将一个 getter 属性另取一个名字,使用对象形式mapGetters({doneCount: ‘doneTodosCount’})

1
2
3
4
5
6
mapGetters({
// 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
//doneCount是doneTodosCount的别名
//'doneTodosCount' 相当于 state => state.doneTodosCount
doneCount: 'doneTodosCount'
})

Mutation(突变):

更改 Vuexstore 中的状态的唯一方法是提交 mutation

类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方

接受 state 作为第一个参数:

1
2
3
4
5
6
7
8
9
10
11
12
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
//type handler
increment (state) {
// 变更状态
state.count++
}
}
})

使用store.commit调用mutation函数

不能直接调用一个 mutation handler(处理程序)

要唤醒一个 mutation handler,需要以相应的 type 调用 store.commit 方法:

1
store.commit('increment')

向store.commit中传递参数:store.commit(‘increment’, {})

可以向 store.commit 传入额外的参数:载荷(Payload)

在大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//基本数据类型
mutations: { //定义
increment (state, n) {
state.count += n
}
}
store.commit('increment', 10) //调用

//对象数据类型
mutations: { //定义
increment (state, payload) {
state.count += payload.amount
}
}
store.commit('increment', { //调用
amount: 10
})
//或者 直接使用包含 type 属性的对象
store.commit({ //调用
type: 'increment',
amount: 10
})

Mutation 需遵守 Vue 的响应规则

  1. 最好提前在 store 中初始化好所有所需属性

  2. 当需要在对象上添加新属性时,你应该

    (1) 使用 Vue.set(obj, 'newProp', 123), 或者

    (2)以新对象替换老对象。例如,利用 对象展开运算符: state.obj = { ...state.obj, newProp: 123 }

使用常量替代 Mutation 事件类型(Mutation Type)

使用常量替代 mutation 事件类型,同时把这些常量放在单独的文件中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// mutation-types.js
export const SOME_MUTATION = 'SOME_MUTATION'

// store.js
import Vuex from 'vuex'
import { SOME_MUTATION } from './mutation-types'

const store = new Vuex.Store({
state: { ... },
mutations: {
// 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名
[SOME_MUTATION] (state,val) {
// mutate state
}
}
})

Mutation 必须是同步函数(不能在里边用定时器及调用接口)

在组件中提交 Mutation

  1. 在组件中使用 this.$store.commit('xxx') 提交 mutation
  2. 使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用(需要在根节点注入 store
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    import { mapMutations } from 'vuex'

    export default {
    // ...
    methods: {
    ...mapMutations([
    'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
    // `mapMutations` 也支持载荷:
    'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
    ]),
    ...mapMutations({
    add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
    })
    }
    }

Action(行动)

Action 类似于 mutation不同在于:

  1. Action 提交的是 mutation,而不是直接变更状态
  2. Action 可以包含任意异步操作

Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象(上下文对象)作为第一个参数

可以调用context.commit提交一个 mutation

通过context.statecontext.getters 来获取 stategetters

context 对象不是 store 实例本身了

payload (实参、有效荷载)作为第二个参数

代码示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
//利用 参数解构 来简化actions代码
actions: {
increment ({ commit }) {
commit('increment')
}
}

分发 Action

Action 通过 store.dispatch 方法触发store.dispatch('increment')

Actions 支持同样的载荷方式和对象方式进行分发store.dispatch('incrementAsync', {})

一个Actions可以派发另一个Actions

1
2
3
4
5
6
7
8
9
10
// 以载荷形式分发
store.dispatch('incrementAsync', {
amount: 10
})

// 以对象形式分发
store.dispatch({
type: 'incrementAsync',
amount: 10
})

购物车实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
actions: {
//context 作为第一个参数,payload (实参、有效荷载)作为第二个参数
//{ commit, state } 利用解构赋值在context中提取到commit, state
//products action执行的时候传过来的实参
checkout ({ commit, state }, products) {
// 把当前购物车的物品备份起来
const savedCartItems = [...state.cart.added]
// 发出结账请求,然后乐观地清空购物车
commit(types.CHECKOUT_REQUEST)
// 购物 API 接受一个成功回调和一个失败回调
shop.buyProducts(
products,
// 成功操作
() => commit(types.CHECKOUT_SUCCESS),
// 失败操作
() => commit(types.CHECKOUT_FAILURE, savedCartItems)
)
}
}

在组件中分发 Action

  1. 在组件中使用 this.$store.dispatch('xxx') 分发 action

  2. 使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用(需要先在根节点注入 store

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { mapActions } from 'vuex'

export default {
// ...
methods: {
...mapActions([
'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`

// `mapActions` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
]),
...mapActions({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
})
}
}

Action 最好通过返回 Promise或者async await 实现异步编程 并 组合 Action

store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch 仍旧返回 Promise

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
actions: {
actionA ({ commit }) {
return new Promise((resolve, reject) => {
setTimeout(() => {
commit('someMutation')
resolve()
}, 1000)
})
}
}

//现在你可以:
store.dispatch('actionA').then(() => {
// ...
})

//在另外一个 action 中也可以:
actions: {
// ...
actionB ({ dispatch, commit }) {
return dispatch('actionA').then(() => {
commit('someOtherMutation')
})
}
}
//最后,如果我们利用 async / await,我们可以如下组合 action:
// 假设 getData() 和 getOtherData() 返回的是 Promise
actions: {
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // 等待 actionA 完成
commit('gotOtherData', await getOtherData())
}
}

Module

store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割

  1. 模块内部的 mutation getter,接收的第一个参数是模块的局部状态对象state

  2. 模块内部的 getter第二个参数其他getter

  3. 模块内部的 getter第三个参数(rootState)根节点状态(根节点state)

  4. 模块内部的 action,局部状态通过 context.state 暴露出来,根节点状态则为 context.rootState

  5. 模块中的state会集成到根节点的state (根节点store).state.(模块名)

  6. 模块内部的 action、mutation 和 getter 是注册在全局命名空间的——这样使得多个模块能够对同一 mutationaction 作出响应,可以像调用根节点的action、mutation 和 getter一样直接调用,也可以 通过namespace用路径访问

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
const moduleA = {
state: { count: 0 },
mutations: {
increment (state) {
// 这里的 `state` 对象是模块的局部状态
state.count++
}
},
getters: {
sumWithRootCount (state, getters, rootState) {
return state.count + rootState.count
}
},
actions: {
incrementIfOddOnRootSum ({ state, commit, rootState }) {
if ((state.count + rootState.count) % 2 === 1) {
commit('increment')
}
}
}
}

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

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

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

组件中获取module中的state数据:this.$store.state.命名空间名称

模块内的状态已经是嵌套的了,使用 namespaced(命名空间)进行获取,只能使用下面方法获取

1
2
3
4
5
6
7
8
9
10
11
12
computed:{
//直接获取
hahh(){
//获取到的是 模块a(moduleA)的state对象
return this.$store.state.a.name
},
//利用语法糖获取
...mapState({
//获取到的是 模块a(moduleA)的state对象
name:state => state.a.name
})
},

组件中获取module中的getter数据:this.$store.getters.aaa

因为模块内部的 getter、mutation 和 action是注册在全局命名空间的 ,不开起namespaced情况下直接获取时不用写model

1
2
3
4
5
6
7
8
9
10
computed:{
//因为模块内部的 action、mutation 和 getter 是注册在全局命名空间的 所以不开起namespaced情况下直接获取时不用写model名
hahh(){
this.$store.getters.aaa
//aaa 可以是任何模块的gettres
},
//利用语法糖获取
//aaa 可以是任何模块的gettres
...mapGetters(['aaa'])
},

命名空间

模块内部的 action、mutation 和 getter 是注册在全局命名空间的,这样使得多个模块能够对同一 mutationaction 作出响应

意思就是:在模块不开起namespaced: true的情况下,调用model中的action、mutation getter就跟调用根节点action、mutation 和 getter是一样的

不开启namespaced的 示例:

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
49
50
51
52
53
54
55
56
57
58
59
60
//store.js
const moduleA = { }
const moduleB = {
state: {
name:'b',
id:'dad'
},
mutations: {
mutat(){
console.log('mutations')
}
},
actions: {
acti(){
console.log('actions')
}
},
getters: {
getname: state=> 'get'+state.name
}
}

export default new Vuex.Store({
state: { },
mutations: { },
actions: { },
modules: {
a: moduleA,
b: moduleB
}
})

//组件内调用
created(){
console.log(this.$store.state.b); //获取b组件的state

//直接调用
this.$store.dispatch('acti')
this.$store.commit('mutat')
console.log(this.$store.getters.getname);

//通过语法糖调用
this.mutat() //运行b组件中的mutat
this.acti() //运行b组件中的acti
console.log(this.getname)
},
computed:{
hahh(){
return this.$store.state.b.name //获取b组件的state
},
...mapState({
name:state => state.b.name //获取b组件的state
}),
//不开启namespaced时获取 模块b 的getname
...mapGetters(['getname'])
},
methods:{
...mapMutations(['mutat']), //不开启namespaced时 获取b组件的mutat
...mapActions(['acti']), //不开启namespaced时 获取b组件的acti
}

开启namespaced(强制getter、mutation、action使用命名空间)

在模块多级嵌套中:不开启namespaced的模块的getter、action 及 mutation会自动挂在在父模块的命名空间

1、开启namespaced的模块会进一步嵌套命名空间

2、通过添加 namespaced: true 的方式使其成为带命名空间的模块

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

模块内的状态已经是嵌套的了,使用 namespaced 属性不会对其产生影响

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
const store = new Vuex.Store({
modules: {
account: {
namespaced: true,

// 模块内容(module assets)
state: { ... }, // 模块内的状态已经是嵌套的了,使用 `namespaced` 属性不会对其产生影响
getters: {
isAdmin () { ... } // -> getters['account/isAdmin']
},
actions: {
login () { ... } // -> dispatch('account/login')
},
mutations: {
login () { ... } // -> commit('account/login')
},

// 嵌套模块
modules: {
//未开启namespaced,会 继承父模块的命名空间
myPage: {
state: { ... },
getters: {
profile () { ... } // -> getters['account/profile']
}
},

//开启了namespaced,会 进一步嵌套命名空间
posts: {
namespaced: true,

state: { ... },
getters: {
popular () { ... } // -> getters['account/posts/popular']
}
}
}
}
}
})

启用了命名空间的 getter 和 action 会收到局部化的(模块内部的) getter,dispatch 和 commit

模块内部(在store.js不是在vue组件内)访问模块自己的getter,dispatch 和 commit不用加路径

在带命名空间的模块内访问全局内容

1、带命名空间的模块内的 getter,要使用全局 stategetter,需要将rootStaterootGetter 会作为第三和第四参数传入 模块内的getter

2、带命名空间的模块内的 action,要使用全局 stategetter,需要通过 context 对象获取,context.rootState 和 context.rootGetters

3、若需要在模块内部 分发 全局命名空间内action 或提交 全局命名空间内mutation,将 { root: true } 作为第三参数传给 dispatchcommit 即可 commit('someMutation', null, { root: true })

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
modules: {
foo: {
namespaced: true,

getters: {
// 在这个模块的 getter 中,`getters` 被局部化了
// 你可以使用 getter 的第四个参数来调用 `rootGetters`
someGetter (state, getters, rootState, rootGetters) {
//调用所在模块内部的getters不需要namespaced
getters.someOtherGetter // -> 'foo/someOtherGetter'
//调用全局getters
rootGetters.someOtherGetter // -> 'someOtherGetter'
},
someOtherGetter: state => { ... }
},

actions: {
// 在这个模块中, dispatch 和 commit 也被局部化了
// 他们可以接受 `root` 属性以访问根 dispatch 或 commit
someAction ({ dispatch, commit, getters, rootGetters }) {
getters.someGetter // -> 'foo/someGetter'
rootGetters.someGetter // -> 'someGetter'

dispatch('someOtherAction') // -> 'foo/someOtherAction'
dispatch('someOtherAction', null, { root: true }) // -> 'someOtherAction'

commit('someMutation') // -> 'foo/someMutation'
commit('someMutation', null, { root: true }) // -> 'someMutation'
},
someOtherAction (ctx, payload) { ... }
}
}
}

在带命名空间的模块注册全局

若需要在带命名空间的模块注册全局 action,可以添加 root: true,并将这个 action 的定义放在函数 handler

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
actions: {
someOtherAction ({dispatch}) {
//就是下面的foo中的someAction
dispatch('someAction')
}
},
modules: {
foo: {
namespaced: true,

actions: {
someAction: {
root: true,
handler (namespacedContext, payload) { ... }
// ->注册全局 'someAction'
}
}
}
}
}

带命名空间的绑定函数(语法糖)

mapState, mapGetters, mapActions 和 mapMutations 这些函数来绑定带命名空间的模块时,写起来可能比较繁琐

1
2
3
4
5
6
7
8
9
10
11
12
computed: {
...mapState({
a: state => state.some.nested.module.a,
b: state => state.some.nested.module.b
})
},
methods: {
...mapActions([
'some/nested/module/foo', // -> this['some/nested/module/foo']()
'some/nested/module/bar' // -> this['some/nested/module/bar']()
])
}
1、可以将模块的空间名称字符串作为第一个参数传递给上述函数,这样所有绑定都会自动将该模块作为上下文mapState(‘some/nested/module’, {})

上面的例子可以简化为:

1
2
3
4
5
6
7
8
9
10
11
12
computed: {
...mapState('some/nested/module', {
a: state => state.a,
b: state => state.b
})
},
methods: {
...mapActions('some/nested/module', [
'foo', // -> this.foo()
'bar' // -> this.bar()
])
}
2、可以通过使用 createNamespacedHelpers 创建基于某个命名空间辅助函数

它返回一个对象,对象里有新的绑定在给定命名空间值上的组件绑定辅助函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//1
import { createNamespacedHelpers } from 'vuex'

//2
const { mapState, mapActions } = createNamespacedHelpers('some/nested/module')

export default {
computed: {
// 在 `some/nested/module` 中查找
...mapState({
a: state => state.a,
b: state => state.b
})
},
methods: {
// 在 `some/nested/module` 中查找
...mapActions([
'foo',
'bar'
])
}
}

模块动态注册store.registerModule

使用 store.registerModule 方法注册模块:

1
2
3
4
5
6
7
8
// 注册模块 `myModule`
store.registerModule('myModule', {
// ...
})
// 注册嵌套模块 `nested/myModule`
store.registerModule(['nested', 'myModule'], {
// ...
})

之后就可以通过 store.state.myModulestore.state.nested.myModule 访问模块的状态

可以使用 store.unregisterModule(moduleName) 来动态卸载模块。注意,你不能使用此方法卸载静态模块(即创建 store 时声明的模块)

在注册一个新 module 时,你很有可能想保留过去的 state,例如从一个服务端渲染的应用保留 state。你可以通过 preserveState 选项将其归档:store.registerModule('a', module, { preserveState: true })

模块重用

起因:

  1. 创建多个 store,他们公用同一个模块,

  2. 在一个 store 中多次注册同一个模块

问题:如果使用一个纯对象来声明模块的状态,因为这个状态对象是引用数据类型当被多处引用时,一个模块改变其他的模块也跟着变,导致状态对象被修改时 store 或模块间数据互相污染的问题。

解决办法:利用函数每次调用互不影响的特性,返回一个对象

1
2
3
4
5
6
7
8
const MyReusableModule = {
state () {
return {
foo: 'bar'
}
},
// mutation, action 和 getter 等等...
}

插件

Vuex 插件就是一个函数,它接收 store 作为唯一参数

在插件中不允许直接修改状态——类似于组件,只能通过提交 mutation 来触发变化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//创建
const myPlugin = store => {
// 当 store 初始化后调用
store.subscribe((mutation, state) => {
// 每次 mutation 之后调用
// mutation 的格式为 { type, payload }
})
}

//使用
const store = new Vuex.Store({
// ...
plugins: [myPlugin]
})

内置 Logger 插件

日志插件

1
2
3
4
5
import createLogger from 'vuex/dist/logger'

const store = new Vuex.Store({
plugins: [createLogger()]
})

createLogger 函数的配置项:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const logger = createLogger({
collapsed: false, // 自动展开记录的 mutation
filter (mutation, stateBefore, stateAfter) {
// 若 mutation 需要被记录,就让它返回 true 即可
// 顺便,`mutation` 是个 { type, payload } 对象
return mutation.type !== "aBlacklistedMutation"
},
transformer (state) {
// 在开始记录之前转换状态
// 例如,只返回指定的子树
return state.subTree
},
mutationTransformer (mutation) {
// mutation 按照 { type, payload } 格式记录
// 我们可以按任意方式格式化
return mutation.type
},
logger: console, // 自定义 console 实现,默认为 `console`
})

表单处理( 双向数据绑定问题)

由于这个修改不是在 mutation 函数中执行的, 这里会抛出一个错误。

解决方法:给 <input> 中绑定 value,然后侦听 input 或者 change 事件,在事件回调中调用 action

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//方法1
<input :value="message" @input="updateMessage">

// ...
computed: {
...mapState({
message: state => state.obj.message
})
},
methods: {
updateMessage (e) {
this.$store.commit('updateMessage', e.target.value)
}
}

// ...
mutations: {
updateMessage (state, message) {
state.obj.message = message
}
}

使用带有 setter 的双向绑定计算属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//方法2  使用带有 setter 的双向绑定计算属性

<input v-model="message">
// ...
computed: {
message: {
get () {
return this.$store.state.obj.message
},
set (value) {
this.$store.commit('updateMessage', value)
}
}
}

项目结构

Alt text

index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import Vue from 'vue';
import Vuex from 'vuex';
import createLogger from 'vuex/dist/logger';

import * as actions from './actions';
import * as getters from './getters';
import state from './state';
import mutations from './mutations';

Vue.use(Vuex);

//判断是否为开发环境
const debug = process.env.NODE_DEV !== 'production';

export default new Vuex.Store({
state,
actions,
getters,
mutations,
strick:debug,
plugins:debug?[createLogger()]:[]
})

state.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//状态树
let project;
if(sessionStorage.getItem('project')){
project=JSON.parse(sessionStorage.getItem('project'))
}else{
project={}
}

const state = {
project:project,
pop:false
}

export default state;

getter.js

1
2
3
//从这里取state取数据 到组件中
export const project = state => state.project;
export const pop = state => state.pop;

mutation-types.js

1
2
3
4
//一些字符串常量
export const SET_PROJECT = 'SET_PROJECT';

export const SET_POP = 'SET_POP';

mutation.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//定义修改的操作  修改state中的数据
import * as types from './mutation-types'

const mutations={
[types.SET_PROJECT](state,project){
sessionStorage.setItem('project',JSON.stringify(project))
state.project=project;
},
[types.SET_POP](state,val){
if(state.addDisable){
return;
}
if(val==1){
state.pop=! state.pop;
}else{
state.pop=false;
}
},
}

export default mutations;

actions.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//异步操作  更改store的状态

const actions = {
//context 作为第一个参数,payload (实参、有效荷载)作为第二个参数
//{ commit, state } 利用解构赋值在context中提取到commit, state
//products action执行的时候传过来的实参
checkout ({ commit, state }, products) {
// 把当前购物车的物品备份起来
const savedCartItems = [...state.cart.added]
// 发出结账请求,然后乐观地清空购物车
commit('increment')
// 异步调用 购物 API 接受一个成功回调和一个失败回调
shop.buyProducts(
products,
// 成功操作
() => commit(types.CHECKOUT_SUCCESS),
// 失败操作
() => commit(types.CHECKOUT_FAILURE, savedCartItems)
)
}
}
export default actions;