modules.png

一、拆分modules

  1. //count.js
  2. const count = {
  3. state: {
  4. count: 0
  5. },
  6. mutations: {
  7. increase(state) {
  8. state.count += 1;
  9. },
  10. decrease(state) {
  11. state.count -= 1;
  12. }
  13. },
  14. actions: {
  15. myIncrease(ctx) {
  16. ctx.commit("increase")
  17. },
  18. myDecrease(ctx) {
  19. ctx.commit("decrease")
  20. }
  21. },
  22. getters: {
  23. myCount(state) {
  24. return `当前计数为:${state.count}`
  25. }
  26. }
  27. }
  28. export default count;
  1. //city.js
  2. const city = {
  3. state:{
  4. defaultCity:"武汉"
  5. }
  6. }
  7. export default city;

二、store/index.js中导入

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

三、使用

  1. <template>
  2. <div class="home">
  3. <h1>首页</h1>
  4. <h2>{{count}}</h2>
  5. <h3>{{myCount}}</h3>
  6. <h2>{{city}}</h2>
  7. </div>
  8. </template>
  9. <script>
  10. import {mapState,mapGetters} from 'vuex';
  11. export default {
  12. name: 'home',
  13. computed:{
  14. ...mapState({
  15. count:state=>state.count.count,
  16. city:state=>state.city.defaultCity
  17. }),
  18. ...mapGetters(['myCount'])
  19. }
  20. }
  21. </script>

3-1 方法照常使用

  1. <template>
  2. <div class="about">
  3. <h1>{{this.$store.state.count.count}}</h1>
  4. <button @click="add">增加</button>
  5. <button @click="reduce">减少</button>
  6. </div>
  7. </template>
  8. <script>
  9. import {mapActions} from 'vuex';
  10. export default {
  11. methods:{
  12. ...mapActions(['myIncrease','myDecrease']),
  13. add(){
  14. this.myIncrease()
  15. },
  16. reduce(){
  17. this.myDecrease()
  18. }
  19. }
  20. }
  21. </script>