Vuex为了解决状态特别多造成store对象非常复杂的时候,允许将store分割成模块(module)
每个模块都可以拥有自己的state、mutation、action、getter
namespaced 命名空间关键字(用在模块的js文件里)
namespaced : true
export default const homeModule ={
namespaced:true ,// 命名空间
state(){
return {
homeCounter:100,
}
},
getters:{
// 命名空间里面,getters,新增了2个参数 rooteState,rootGetters
doubleHomeCounter(state){
return state.homeCounter*2
}
},
mutations:{
increment(state,payload){
state.homeCounter++
}
},
actions:{
incrementAction({commit}){
commit("increment")
commit("increment",null,{root:true}) // 在模块里调用state根的mutations里面的方法
}
}
}
import {createStore} from 'vuex'
import homeModule from './modules/home'
const store = createStore({
state(){
return{
rootCounter:0
}
},
mutaions:{
increment(state){
state.rootCounter++
}
},
modules:{
home:homeModule
}
})
export default store
state根数据: {{$store.state.rootCounter}}
home 模块中的数据:{{$store.state.home.homeCoutner}}
doubleCounter {{$store.getters["home/doubleHomeCounter"]}}
关键代码 :
const {mapState,mapGetters,mapMutations,mapActions} = createNamespacedHelpers("home")
{{homeCounter}}
{{doubleHomeCounter}}
组件内使用模块的三种写法
computed:{
...mapState({
homeCounter:state => state.homeCounter
}),
...mapGetters({
doubleHomeCounter :"home/doubleHomeCounter"
})
}
methods:{
...mapMutations({
increment:"home/increment"
}),
...mapActions({
incrementAction:"home/incrementAction"
})
}
computed:{
...mapState("home",["homeCounter"]),
...mapGetters("home",["doubleHomeCounter"])
},
methods:{
...mapMutations("home",["increment"]),
...mapActions("home",["incrementAction"]),
}
import {createNamespacedHelpers} from 'vuex'
const {mapState,mapGetters,mapMutatons,mapActions} = createNamespacedHelpers("home")
computed:{
...mapState(["homeCounter"]),
...mapGetters(["doubleHomeCounter"])
},
methods:{
...mapMutations(["increment"]),
...mapActions(["incrementAction"]),
}
在 setup里使用
setup(){
const state = useState(["homeCounter"])
const getters = useGetters(["doubleHomeCounter"])
const mutations = mapMutations(["increment"])
const actions = mapActions(["incrementAction"])
retrn{
...state,
...getters,
...mutations,
...actions
}
}
useState.js 支持模块化数据
import {mapState,createNamespacedHelpers} from 'vuex'
import {useMappers} from './useMappers'
export function useState(moduleName,mapper){
let mapperFn = mapState
if(typeof moduleName === 'string' && moduleName.length>0){
mapperFn = createNamespacedHelpers(moduleName).mapState ;// moduleName 就是模块的名字
}else{
mapperFn = moduleName
}
return useMapper(mapper,mapperFn)
}
useMapper.js (没改)
import {computed} from 'vue'
import {useStore} from 'vuex'
export function useMapper(mapper,mapFn){
const store = useStore()
const storeStateFns = mapFn(mapper) // 如果是useState调用的,那么这里就相当于 mapState(传过来的要拿的state名称,可能是数组可能是对象,返回结果是一个对象 {name:function,age:function}
const storeState = {}
Object.keys(storeStateFns).forEach(fnKey =>{
const fn = storeStateFns[fnKey].bind({$store:store})
storeState[fnKey] = computed(fn)
})
return storeState
}