新建vue项目       

vue vuex module进阶语法_javascript

 main.js

import Vue from 'vue'
import App from './App.vue'
import store from '@/store'

Vue.config.productionTip = false;

new Vue({
  render: h => h(App),
  store
}).$mount('#app');

app.vue

<template>
  <div id="app">
    <h1>vuex modules</h1>
    <base-a></base-a>
    <base-b></base-b>
  </div>
</template>

<script>
import BaseA from "@/components/BaseA";
import BaseB from "@/components/BaseB";

export default {
  name: 'App',
  components: {
    BaseA,
    BaseB
  },
  created() {
    console.log(this.$store);
  }
}
</script>

<style>

</style>

index.js

import Vue from 'vue'
import Vuex from 'vuex'
import user from "@/store/modules/user";
import setting from "@/store/modules/setting";

Vue.use(Vuex);

const store = new Vuex.Store({
    modules:{
        user,
        setting
    }
});

export default store

user.js

//user模块
const state = {
    userInfo: {
        name:'zhang',
        age:18
    },
    score:80
};
const mutations = {};
const actions = {};
const getters = {};

export default {
    //开启命名空间
    namespaced:true,
    state,
    mutations,
    actions,
    getters
}

//使用模块中的数据
//1 直接通过模块名访问 $store.state.模块名.xxx
//2 通过 mapState映射
//  默认根级别的映射 mapState(['xxx])
//  子模块的映射 mapState('模块名',['xxx'])

setting.js

//setting模块
const state = {
    theme:'light',
    desc:'测试demo'
};
const mutations = {};
const actions = {};
const getters = {};

export default {
    //开启命名空间
    namespaced:true,
    state,
    mutations,
    actions,
    getters
}

BaseA.vue

<template>
    <div class="base-a">
        <!-- 通过原生的方式       -->
        <div>{{ $store.state.user.userInfo.name }}</div>
        <div>{{ $store.state.setting.theme }}</div>
    </div>
</template>

<script>
    export default {
        name: "BaseA"
    }
</script>

<style scoped>

</style>

BaseB.vue

<template>
    <div class="base-b">
        <!-- 通过map等方式       -->
        <div>{{ user.userInfo }}</div>
        <div>{{ setting.theme }}</div>
        <div>user模块的数据:{{ userInfo.name }}</div>
        <div>setting模块的数据:{{ theme }}--{{ desc }}</div>
    </div>
</template>

<script>
    import { mapState } from 'vuex'
    export default {
        name: "BaseB",
        computed:{
            ...mapState(['user','setting']),
            ...mapState('user',['userInfo','score']),
            ...mapState('setting',['theme','desc'])
        }
    }
</script>

<style scoped>

</style>

vue vuex module进阶语法_javascript_02