vuex命名空间模块化

 

目录结构

modules/app.js

export default {
  namespaced: true,
  state: {
    token: 'notoken'
  },
  getters: {

  },
  mutations: {
    changeToken(state, res) {
      state.token = res
    }
  },
  actions: {}
}

modules/shop.js

export default {
  namespaced: true,
  state: {
    count: 80
  },
  getters: {

  },
  mutations: {
    changeCount(state, res) {
      state.count = res
    }
  },
  actions: {}
}

modules/index.js

import app from './app.js'
import shop from './shop.js'
export default {
  app,
  shop
}

 

store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import modules from './modules'

Vue.use(Vuex)


const store = new Vuex.Store({
  modules,
})

export default store

 

页面中使用

app.vue

<template>
  <div id="app">
    <h1>{{ token }}</h1>
    <h1>{{ count }}</h1>
  </div>
</template>

<script>
import { createNamespacedHelpers } from 'vuex'
const { mapState, mapMutations } = createNamespacedHelpers('app')
const shopStore = createNamespacedHelpers('shop')
export default {
  name: 'App',
  computed: {
    ...mapState(['token']),
    ...shopStore.mapState(['count'])
  },
  data() {
    return {
      flag: false
    }
  },
  methods: {
    obj1(res) {
      this.flag = res
    },
    ...mapMutations(['changeToken']),
    ...shopStore.mapMutations(['changeCount']),
    login() {
      this.changeToken('token111111')
      this.changeCount(50)
    }
  },
  mounted() {
  }

}
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

 


版权声明:本文为qq_41430522原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。