模块化(modules)和命名空间(namespaced)
1)、vuex模块化的原因:vuex维护的是一个单一的状态树,对于复杂的vue项目,若只有一个store,则该store就会非常臃肿难以维护,为了解决这个问题,vuex允许在vue项目中将store进行模块化的处理,即可以将一个大的store分解成若干个小的store,每个store都有自己的state、mutations、actions、getters
2)、命名空间:
(1)在默认情况下,模块内部的state、mutation、action、getter是全局的,即所有组件都可以使用
(2)若想让store有更好的封装性和复用性、在使用不会产生歧义,可以在store定义时加入 namespaced:true配置,当模块注册
在src下新建一个文件夹store,然后在store文件夹下再新建一个文件夹login,存放登录注册相关的状态机
src/store/index.js
import Vue from "vue";
import Vuex from 'vuex';
import login from './login/login';
import register from './login/register';
Vue.use(Vuex)
export default new Vuex.Store({
state:{},
getters:{},
mutations:{},
actions:{},
modules:{
login,
register
}
})
src/store/login/login.js
import axios from 'axios';
export default {
namespaced:true,//模块化必须加,为了在其他页面用到的时候加模块名。
state:{
lname:"用户一"
},
getters:{
fullNmae(state){
return state.lname+'111';
}
},
mutations:{
updateName(state,obj){
console.log(obj);
state.lname = obj.lname;
}
},
actions:{
actionUpdateName(context,obj){
console.log(obj);
context.commit('updateName',obj)
}
},
}
Vue.use(Vuex)):main.js 注入仓库
import Vue from 'vue'
import App from './App'
//当前处于开发阶段,无需显示生产模式提示的信息。
Vue.config.productionTip = false;
import VueRouter from 'vue-router';
Vue.use(VueRouter);
import routes from './router/index';
import store from './store/index';
new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
模块化取值
获取数据项: {{$store.state.模块名.数据项名}}
获取getters: {{$store.getters['模块名/getters名']}}
this.$store.state.login.lname
this.$store.getters['login/fullNmae']
<template>
<div id="home">
<p>{{msg1}}</p>
<p>{{msg2}}</p>
<p @click="upname">更换名字</p>
</div>
</template>
<script>
export default {
data () {
return {
}
},
computed:{
msg1:function(){
return this.$store.state.login.lname;
},
msg2:function(){
return this.$store.getters['login/fullNmae'];
}
},
methods:{
upname:function(){
this.$store.commit('login/updateName',{'lname':'用户无'})
//actions需要通过dispatch来响应
this.$store.dispatch('login/actionUpdateName',{'lname':'用户无'})
}
}
}
</script>
<style>
</style>
modules下辅助函数
<template>
<div id="home">
<p>{{msg1}}</p>
<p>{{msg2}}</p>
<p @click="upname">更换名字</p>
</div>
</template>
<script>
import { mapState, mapGetters, mapActions, mapMutations } from 'vuex';
export default {
data () {
return {
}
},
computed:{
...mapState({'msg1':state=>state.login.lname}),
...mapGetters({'msg2':'login/fullNmae'})
},
methods:{
...mapMutations({
upname(commit){
commit('login/updateName',{'lname':'用户无'})
}
}),
...mapActions({
upname(dispatch){
dispatch('login/actionUpdateName',{'lname':'用户无'})
}
})
}
</script>