作用:当store对象非常复杂的时候,我们可以根据将其拆分成不同的模块

6.1新建modules文件夹,拆分store/index.js

image.png

1.新建modules/info.js—消息和user.js—用户

  1. //info.js
  2. const info = {
  3. state: {
  4. tips:12,
  5. news:8
  6. },
  7. mutations: {
  8. },
  9. actions: {},
  10. getters: {}
  11. }
  12. export default info;
  1. //user.js
  2. const user = {
  3. state: {
  4. name:"王思曼"
  5. },
  6. mutations: {},
  7. actions: {},
  8. getters: {}
  9. }
  10. export default user;

2.将info.js和user.js导入到index.js中

  1. import Vue from 'vue'
  2. import Vuex from 'vuex'
  3. import user from './modules/user';
  4. import info from './modules/info';
  5. Vue.use(Vuex)
  6. export default new Vuex.Store({
  7. modules:{
  8. user,
  9. info
  10. }
  11. })

6.2使用数据

  1. <template>
  2. <div class="home">
  3. <h2>首页</h2>
  4. <h3>{{tips}}</h3>
  5. <h4>{{news}}</h4>
  6. <h5>{{name}}</h5>
  7. <button @click="add">增加</button>
  8. <button @click="reduce">减少</button>
  9. </div>
  10. </template>
  11. <script>
  12. import {mapState, mapMutations} from 'vuex'
  13. export default {
  14. name: 'home',
  15. computed:{
  16. ...mapState({
  17. tips:state=>state.info.tips,
  18. news:state=>state.info.news,
  19. name:state=>state.user.name,
  20. })
  21. },
  22. methods:{
  23. ...mapMutations(['add','reduce'])
  24. }
  25. }
  26. </script>