目的:由于Vuex使用的是单一状态树,所有的应用状态都会集中到一个比较大的对象。所以我们拆分store,每一个组件的store创建一个单独的模块,便于维护。

1.创建modules文件夹

 2.配置子模块

const state = {
    userInfo :{
        name : '巧克力的雨天',
        age : 9,
        score : 10998
    }
}
const mutations = {}
const actions = {}
const getters = {}

export default {
    state,mutations,actions,getters
}

3.引入到store/index主模块中

import user from './modules/user'
import setter from './modules/setter'
const store = new Vuex.Store({
    strict : true,
    state : { },
    mutations : {},
    actions : {   },
    getters : {},
    modules : {
        user,setter
    }
})

4.访问子模块中的状态state

尽管已经分模块了,但是子模块的状态还是会挂在跟级别的state中,属性名就是模块名

(1)直接通过模块名访问 $store.state.模块名.XXX

 <div :style="{color:$store.state.setter.theme}">
        {{ $store.state.user.userInfo.name }}
        {{ $store.state.setter.theme }}
      </div>

(2)通过mapState映射,需要开启命名空间

-第一种

 computed: {
    ...mapState(['user','setter']),
  },
 <div :style="{ color: setter.theme }">
        {{ user.userInfo.name }}
        {{ setter.theme }}
      </div>

-第二种

    ...mapState('user',['userInfo']),
    ...mapState('setter',['theme']),

<div :style="{ color: theme }">
        {{ userInfo.name }}
        {{ theme }}
  </div>

5.访问getters

(1)直接通过模块名访问

const state = {
    userInfo :{
        name : '巧克力的雨天',
        age : 9,
        score : 10998,
        id : 'iiiiiuuuuu'
    }
}
const mutations = {}
const actions = {}
const getters = {
    //分模块后 state参数指的是自己模块的state
    idUpper(state){
        return state.userInfo.id.toUpperCase()
    }
}

export default {
    namespaced : true, //开启命名空间
    state,mutations,actions,getters
}
<div>
   {{ $store.getters['user/idUpper'] }}
</div>

(2)通过mapGetters映射

  computed: {
    ...mapGetters('user',['idUpper'])
  },

 <div>
        {{ idUpper }}
  </div>

6.mutation

注意:默认模块中的mutation和actions会背挂载到全局,需要开启命名空间,才会被挂载到子模块

(1)直接通过store调用

const mutations = {
    changeTheme(state,n){
        state.theme = n
    }
}
<button @click="changeTheme">
          改theme
 </button>


methods: {

    changeTheme(){
      // this.$store.commit('模块名/mutation名',参数)
      this.$store.commit('setter/changeTheme','blue')
    }
  }

(2)通过mapMutations映射

 methods: {
    ...mapMutations('setter',['changeTheme']),

  }


<button @click="changeTheme('black')">
          改theme
 </button>

6.action(同mutation)

(1)直接调用

 

const mutations = {
    changeTheme(state,n){
        state.theme = n
    }
}
const actions = {
    changeColor(context,n){
        setTimeout(() => {
            context.commit('changeTheme',n)
        }, 2000);
    }
}

 

 changeColor(){
    this.$store.dispatch('setter/changeColor','red')
 }


<button @click="changeColor">
          2s后改theme
 </button>

(2)通过mapActions映射

 ...mapActions('setter',['changeColor']),

<button @click="changeColor('green')">
          2s后改theme
</button>

 

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。