Vuex 模块化 store和namespaced

一、模块化

1、几个组件定义几个对象

文件 src/store/index.js

// 与count组件相关的optinos
const  countOptions = {
    actions:{},
    mutations:{},
    state:{},
    getters:{}
}
// 与person组件 相关的options
const personOptions = {
    actions:{},
    mutations:{},
    state:{},
    getters:{}
}

2、把之前相关联的内容填充,注意每个对象都要加 namespaced: true,

// 与count组件相关的optinos
const  countOptions = {
namespaced: true, actions:{ addOdd(context, value){
if(context.state.sum % 2){ context.commit('ADD', value) } }, addWait(context, value){ setTimeout(() => { context.commit('ADD', value) }, 500) } }, mutations:{ ADD(state, value){ // console.log(state.sum, value) state.sum += value }, SUB(state, value){ state.sum -= value }, }, state:{ sum:0, name: "jojo", }, getters:{ bigSum(state){ return state.sum * 10 } } } // 与person组件 相关的options const personOptions = {
namespaced: true, actions:{}, mutations:{ ADD_PERSON(state, value){ state.personLst.unshift(value) }, }, state:{ personLst:[{id:
"001", name:"张三"}] }, getters:{} }

3、修改暴露  使用 modules

export default new Vuex.Store({
    modules:{
        countOptions,
        personOptions
    }
})

二、使用

1、 state 和 getters

a、原生

computed:{
    // 原生state中值
    sum(){
        return this.$store.state.countOptions.sum
    },
    personLst(){
        return this.$store.state.personOptions.personLst
    },
    // 原生getters中值
    firstPersonName(){
        return this.$store.getters['personOptions/firstPersonName']
    }
},

b、借助 map

computed:{
    ...mapState('countOptions' ,['name', 'sum']),
    ...mapState('personOptions', ["personLst"]),
    ...mapGetters('countOptions',["bigSum"])
}

2、actions和mutations

a、原生

// 原生dispatch -> actions
addPersonWang(){
    const person = {id:nanoid(), name:this.name}
    this.$store.dispatch('personOptions/addPersonWang', person)
},

// 原生commit -> mutattions
addPerson(){
    const person = {id: nanoid(), name:this.name}
    // this.personLst.unshift(person)
    this.$store.commit("personOptions/ADD_PERSON", person)
    this.name =""
},

b、借助 map

methods:{
    ...mapActions('countOptions',{addNumOdd:"addOdd", addNumWait:"addWait"}),
    ...mapMutations('countOptions',{addNum:"ADD", subisNum:"SUB"}),
}

 

posted @ 2025-01-08 08:41  市丸银  阅读(40)  评论(0)    收藏  举报