模块化,只针对于超大型项目
index.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const state = {
count:44
}
const mutations ={
jia(state,n){
state.count+=n.a;
},
jian(state){
state.count--
}
}
//vue 2.0官方建议在computed里面的不使用箭头函数,因为箭头函数的this 指向上一层,而function的this指向本层
const getters={
count:function(state){
return state.count+=100
}
}
const actions={
//context在actions里面代表着整个的store
jiaplus(context){
context.commit('jia',{a:1});
setTimeout(() => {
context.commit('jian');
}, 1000);
console.log('我先被执行了')
},
jianplus({commit}){
commit('jian')
}
}
const moduleA = {
state,
mutations,
getters,
actions
}
const moduleB = {
state:{
count:144
}
}
export default new Vuex.Store({
modules:{
a:moduleA,
b:moduleB
}
})
vue
<style>
p button{
width: 50px;
}
</style>
<template>
<div>
<div>
{{$store.state.a.count}}-{{count}}-{{$store.state.b.count}}
</div>
<p>
</p>
</div>
</template>
<script>
export default {
name:'te',
data(){
return{
counts:0
}
},
computed: {
count () {
return this.$store.state.a.count+1
}
},
methods:{
}
}
</script>
比如是app模块下的state的roleName,读取的时候2种写法,可以看到辅助函数更麻烦
import { mapState } from 'vuex' computed: { ...mapState({ "roleName": state => state.app.roleName }), // roleName () { // return this.$store.state.app.roleName // } },