作用:当store对象非常复杂的时候,我们可以根据将其拆分成不同的模块
6.1新建modules文件夹,拆分store/index.js
1.新建modules/info.js—消息和user.js—用户
//info.js
const info = {
state: {
tips:12,
news:8
},
mutations: {
},
actions: {},
getters: {}
}
export default info;
//user.js
const user = {
state: {
name:"王思曼"
},
mutations: {},
actions: {},
getters: {}
}
export default user;
2.将info.js和user.js导入到index.js中
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user';
import info from './modules/info';
Vue.use(Vuex)
export default new Vuex.Store({
modules:{
user,
info
}
})
6.2使用数据
<template>
<div class="home">
<h2>首页</h2>
<h3>{{tips}}</h3>
<h4>{{news}}</h4>
<h5>{{name}}</h5>
<button @click="add">增加</button>
<button @click="reduce">减少</button>
</div>
</template>
<script>
import {mapState, mapMutations} from 'vuex'
export default {
name: 'home',
computed:{
...mapState({
tips:state=>state.info.tips,
news:state=>state.info.news,
name:state=>state.user.name,
})
},
methods:{
...mapMutations(['add','reduce'])
}
}
</script>