Module的用法(终篇)

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

如何使用module

在store文件夹下新建modules文件夹,并在下面建立moduleA.js和moduleB.js文件用来存放vuex的modules模块

moduleA.js文件内容如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

const state = {

  stateA: 'A'

}

 

const mutations = {

  showA (state) {

    return state.stateA

  }

}

 

const actions = {

  showAAction (context) {

    context.commit('showA')

  }

}

 

const getters = {

  getA (state) {

    return state.stateA

  }

}

 

export default {state, mutations, actions, getters}

moduleB.js文件内容如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

const state = {

  stateB: 'B'

}

 

const mutations = {

  showA (state) {

    return state.stateB

  }

}

 

const actions = {

  showAAction (context) {

    context.commit('showB')

  }

}

 

const getters = {

  getA (state) {

    return state.stateB

  }

}

 

export default {state, mutations, actions, getters}

store.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 state from './state'

import mutations from './mutations'

import getters from './getters'

import actions from './actions'

import moduleA from './modules/moduleA'

import moduleB from './modules/moduleB'

 

Vue.use(Vuex)

 

const store = new Vuex.Store({

  state,

  mutations,

  getters,

  actions,

  modules: {

    moduleA,

    moduleB

  }

 

export default store

在组件中使用

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

<template>

  <div class="modules">

    <h1>{{moduleA}}  ---  {{moduleB}}</h1>

  </div>

</template>

 

<script>

import { mapState } from 'vuex'

 

export default {

  data () {

    return {}

  },

  computed: {

    ...mapState({

      moduleA:  state => state.moduleA.stateA,

      moduleB:  state => state.moduleB.stateB

    })

  }

}

</script>

模块动态注册

在 store 创建之后,你可以使用 store.registerModule 方法注册模块:

1

2

3

4

5

6

7

8

// 注册模块 `myModule`

store.registerModule('myModule', {

  // ...

})

// 注册嵌套模块 `nested/myModule`

store.registerModule(['nested''myModule'], {

  // ...

})

之后就可以通过 store.state.myModule 和 store.state.nested.myModule 访问模块的状态。模块动态注册功能使得其他 Vue 插件可以通过在 store 中附加新模块的方式来使用 Vuex 管理状态。例如,vuex-router-sync 插件就是通过动态注册模块将 vue-router 和 vuex 结合在一起,实现应用的路由状态管理。你也可以使用 store.unregisterModule(moduleName) 来动态卸载模块。注意,你不能使用此方法卸载静态模块(即创建 store 时声明的模块)。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值