vuex 다 중 모듈 시 모듈 내부 의 mutation 과 action 호출 방식

vue 는 대형 프로젝트 를 할 때 다 중 상태 관 리 를 사용 합 니 다.vuex 는 store 를 여러 모듈 로 나 눌 수 있 습 니 다.각 모듈 에는 자신의 state,mutation,action,getter 가 있 습 니 다.모듈 안에 대응 하 는 서브 모듈 도 계속 끼 워 넣 을 수 있다.
store 다 중 모듈 에 대한 기본 적 인 인식 을 공 고 히 하기 위해 간단 한 다 중 모듈 인 스 턴 스 를 썼 습 니 다.다음 그림 은 제 가 만 든 store 의 디 렉 터 리 구조,modules 폴 더 안의 모듈 입 니 다.실제 프로젝트 에서 store 디 렉 터 리 와 같은 다 중 파일 구성,즉 단독 모듈 폴 더 를 계속 분리 하여 후기 수정 에 편리 합 니 다.

store 디 렉 터 리 구조
./store/index.js 의 코드 는 다음 과 같 습 니 다.

import Vue from 'vue'
import Vuex from 'vuex'
// import mutations from './mutations'
import modulesA from './modules/modulesA'
import modulesB from './modules/modulesB'
 
Vue.use(Vuex)
 
const state = {
 logined: false,
 userid: -1
}
 
const store = new Vuex.Store({
 state,
 mutations: {
  'UPDATE_LOGIN_STATUS': (state, payload) => {
   state.logined = true
  }
 },
 modules: {
  modulesA: modulesA,
  modulesB: modulesB
 }
})
 
export default store
여기 서 하위 모듈 과 비교 하기 위해 서 저 는 mutations.js 코드 를 index.js 에 넣 었 습 니 다.
modules A.js 의 코드 는 다음 과 같 습 니 다.

const moduleA = {
 namespaced: true,
 state: {
  isVip1: false
 },
 mutations: {
  'UPDATE_TO_VIP1': (state, payload) => {
   state.isVip1 = true
  }
 },
 actions: {
  getVip1 ({ state, commit, rootState }) {
   commit('UPDATE_TO_VIP1')
  }
 },
 getters: {}
}
export default moduleA
modules B.js 의 코드 는 다음 과 같 습 니 다.

const moduleB = {
 // namespaced: true,
 state: {
  isVip2: false
 },
 mutations: {
  'UPDATE_TO_VIP2': (state, payload) => {
   state.isVip2 = true
  }
 },
 actions: {
  getVip2 ({ state, commit, rootState }) {
   commit('UPDATE_TO_VIP2')
  }
 },
 getters: {}
}
export default moduleB
아마 이곳 을 보면 modules A 와 modules B 의 차 이 는 namespaced 라 는 속성 이 있 는 지 없 는 지 를 발견 할 수 있 을 것 이다.vuex 에 서 는 모듈 내부 의 action,mutation,getter 가 전체 네 임 스페이스 에 등 록 됩 니 다.속담 에 전역 으로 등 록 된 것 이 라 고 합 니 다.이러한 결 과 는 해당 하 는 이름 의 action 이나 mutation 또는 getter 를 호출 할 때 모든 동명 의 응답 이 됩 니 다.namespaced(또는 값 이 false)가 없 을 때 구성 요소 에서 어떻게 호출 되 는 지 보 겠 습 니 다.코드 는 다음 과 같 습 니 다.

<template>
 <div class="hello">
  <h1>{{ msg }}</h1>
  <ul>
   <li>global state <strong>logined</strong>: {{ globalState }}</li>
   <li>modulesA state <strong>isVip1</strong> {{ modulesAState }}</li>
  </ul>
 </div>
</template>
 
<script>
export default {
 name: 'test',
 data () {
  return {
   msg: 'Test vuex mutilple modules'
  }
 },
 created () {
  console.log(this.$store.state)
  setTimeout(() => {
   this.$store.commit('UPDATE_LOGIN_STATUS')
  }, 1000)
  setTimeout(() => {
   this.$store.commit('UPDATE_TO_VIP1')
   // this.$store.dispatch('getVip1')
  }, 2000)
  setTimeout(() => {
   // this.$store.commit('CANCEL_VIP1')
   this.$store.dispatch('cancelVip1')
  }, 3000)
 },
 computed: {
  globalState () {
   return this.$store.state.logined
  },
  modulesAState () {
   return this.$store.state.modulesA.isVip1
  }
 }
}
</script>
 
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
실행 코드 캡 처 는 다음 과 같 습 니 다.

보 실 수 있 습 니 다.저 는 store 에서 upDATE 를 커밋 합 니 다.LOGIN_STATUS,최상 위 state 의 logined 값 을 true 로 변경 합 니 다.2s 때 store 에서 UPDATE 를 커밋 했 어 요.TO_VIP 1 과 3s 때 dispatch 이벤트 가 하나 생 겼 어 요.CANCELVIP 1,modules A 의 isVip 1 값 을 false=>true=>false 에서 사용 합 니 다.네 임 스페이스 가 열 리 지 않 은 것 은 commt 또는 dispatch 서브 모듈 에 대응 하 는 방법 명 으로 자신의 state 속성 을 수정 할 수 있 음 을 설명 합 니 다.
namespaced 의 값 이 true 일 때 네 임 스페이스 모듈 을 열 었 습 니 다.하위 모듈 의 getter,mutation,getter 를 호출 할 때 이전 과 다 릅 니 다.vuex 내부 에 서 는 모듈 등록 경로 에 따라 자동 으로 이름 을 조정 합 니 다.예 를 들 어 dispatch B 중의 action 을 호출 하려 면 구성 요소 내 호출 은 다음 과 같 아야 합 니 다.
// this.$store.dispatch('modulesB/getVip2')
this.$store.commit('modulesB/UPDATE_TO_VIP2')
일상 프로젝트 에서 store 가 여러 상 태 를 관리 해 야 할 때 일반적으로 namespaced 를 켜 야 합 니 다.이렇게 하면 우리 의 코드 가 더욱 강 한 패 키 징 성과 더 적은 결합 을 가 질 수 있 습 니 다.
추가 지식:Vuex 모듈 화+네 임 스페이스 후 다른 모듈 의 state,actions,mutations,getters 를 어떻게 호출 합 니까?
Vuex 가 단일 상태 트 리 를 사 용 했 기 때문에 모든 상태 가 하나의 큰 대상 에 포 함 됩 니 다.그러면 애플 리 케 이 션 이 확장 되면 서 store 는 비대 해 집 니 다.
이 문 제 를 해결 하기 위해 Vuex 는 store 를 module(모듈)로 나 눌 수 있 도록 합 니 다.각 모듈 은 각자 의 상태,mutation,action,getter 를 포함한다.
그러면 문제 가 발생 했 습 니 다.모듈 화+네 임 스페이스 이후 데 이 터 는 상대 적 으로 독립 되 었 습 니 다.모듈 A 에서 모듈 B 의 state,actions,mutations,getters 를 호출 하려 면 어떻게 해 야 합 니까?
만약 에 이런 두 개의 모듈 이 있다 고 가정 하면:
모듈 A:

import api from '~api'

const state = {
  vip: {},
}

const actions = {
  async ['get']({commit, state, dispatch}, config = {}) {
    try {
      const { data: { code, data } } = await api.post('vip/getVipBaseInfo', config)
      if (code === 1001) commit('receive', data)
    } catch(error) { console.log(error) }
  }
}

const mutations = {
  ['receive'](state, data) {
    state.vip = data
  }
}

const getters = {
  ['get'](state) {
    return state.vip
  },
}

export default {
  namespaced: true,
  state,
  actions,
  mutations,
  getters
}
모듈 B:

import api from '~api'

const state = {
  shop: {},
}

const actions = {
  async ['get']({commit, state, dispatch}, config = {}) {
    try {
      const { data: { code, data } } = await api.post('shop/getShopBaseInfo', config)
      if (code === 1001) commit('receive', data)
    } catch(error) { console.log(error) }
  }
}

const mutations = {
  ['receive'](state, data) {
    state.shop = data
  }
}

const getters = {
  ['get'](state) {
    return state.shop
  },
}

export default {
  namespaced: true,
  state,
  actions,
  mutations,
  getters
}
모듈 B 의 actions 에 모듈 A 의 state 를 사용 해 야 한다 고 가정 하면 어떻게 해 야 합 니까?

const actions = {
  async ['shop'](store, config = {}) {
    const { commit, dispatch, state, rootState } = store
    console.log(rootState) //     state
    console.log(rootState.vip) //         state
    try {
      const { data: { code, data } } = await api.post('shop/getShopBaseInfo', config)
      if (code === 1001) commit('receive', data)
    } catch(error) { console.log(error) }
  }
}
위의 코드 를 살 펴 보 겠 습 니 다.actions 의 shop 방법 은 두 개의 매개 변수 가 있 습 니 다.첫 번 째 는 store 이 고 두 번 째 는 dispatch 호출 시 전 달 된 매개 변수 입 니 다.
store 이 대상 은 4 개의 키 를 포함 하고 있 습 니 다.그 중에서 commt 는 mutations 를 호출 하 는 데 사 용 됩 니 다.dispatch 는 actions 를 호출 하 는 데 사 용 됩 니 다.state 는 현재 모듈 의 state 이 고 rootState 는 루트 state 입 니 다.
루트 state 를 얻 을 수 있 으 니 다른 모듈 의 state 를 얻 으 려 면 간단 하지 않 습 니까?
모듈 B 의 actions 에서 모듈 A 의 actions 를 호출 해 야 한다 고 가정 하면 어떻게 해 야 합 니까?

const actions = {
  async ['shop'](store, config = {}) {
    const { commit, dispatch, state, rootState } = store
    try {
      const { data: { code, data } } = await api.post('shop/getShopBaseInfo', config, 'get')
      if (code === 1001) commit('receive', data) //         mutations
      dispatch('vip/get', {}, {root: true}) //         actions
    } catch(error) { console.log(error) }
  }
}
위의 코드 중 dispatch('vip/vip',{},{root:true})는 모듈 B 에서 모듈 A 를 호출 하 는 actions 입 니 다.
세 개의 매개 변수 가 있 습 니 다.첫 번 째 매개 변 수 는 다른 모듈 의 actions 경로 입 니 다.두 번 째 는 actions 에 전 달 된 데이터 입 니 다.데 이 터 를 전달 할 필요 가 없 으 면 미리 남 겨 두 어야 합 니 다.세 번 째 매개 변 수 는 설정 옵션 입 니 다.이 acitons 는 현재 모듈 의 것 이 아 닙 니 다.
모듈 B 의 actions 에서 모듈 A 의 mutations 를 호출 하려 면 어떻게 해 야 합 니까?

const actions = {
  async ['shop'](store, config = {}) {
    const { commit, dispatch, state, rootState } = store
    try {
      const { data: { code, data } } = await api.post('shop/getShopBaseInfo', config)
      if (code === 1001) commit('receive', data) //         mutations
      commit('vip/receive', data, {root: true}) //         mutations
    } catch(error) { console.log(error) }
  }
}
위의 코드 중 commt(vip/receive,{},{root:true})는 모듈 B 에서 모듈 A 를 호출 하 는 mutations 입 니 다.
3 개의 매개 변수 가 있 습 니 다.첫 번 째 매개 변 수 는 다른 모듈 의 mutations 경로 입 니 다.두 번 째 는 mutations 에 전 달 된 데이터 입 니 다.데 이 터 를 전달 하지 않 아 도 미리 남 겨 두 어야 합 니 다.세 번 째 매개 변 수 는 설정 옵션 입 니 다.이 mutations 는 현재 모듈 이 아 닙 니 다.
모듈 B 의 actions 에 모듈 A 의 getters 를 사용 해 야 한다 고 가정 하면 어떻게 해 야 합 니까?

const actions = {
  async ['shop'](store, config = {}) {
    const { commit, dispatch, state, rootState, rootGetters } = store
    console.log(rootGetters['vip/get']) //         getters
    try {
      const { data: { code, data } } = await api.post('shop/getShopBaseInfo', config)
      if (code === 1001) commit('receive', data)
    } catch(error) { console.log(error) }
  }
}
위의 코드 를 살 펴 보 겠 습 니 다.이전 코드 에 비해 store 에 키 가 하나 더 생 겼 습 니 다:rootGetters
rootGetters 는 vuex 의 모든 getters 입 니 다.rootGetters[xxxx]로 다른 모듈 의 getters 를 가 져 올 수 있 습 니 다.
상기 vuex 다 중 모듈 시 모듈 내부 의 mutation 과 action 의 호출 방식 은 바로 작은 편집 이 여러분 에 게 공유 하 는 모든 내용 입 니 다.여러분 께 참고 가 되 고 저희 도 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기