[GNB카테고리] store in vuex

Question Murder·2022년 9월 2일
0

GNB카테고리를 API데이터를 받아 화면에 부쳐주는 작업을 해볼 것이다. 글은 1편,2편으로 나누고 1편(여기)에서는 api값을 받아 vuex 데이터 상태관리하는 내용에 대해 알아보고 2편에서는 화면에 값을 부쳐 노출시키는 작업을 해볼 것이다.
2편 보러가기

WHAT I AM GONNA DO

  • 기능: API에서 응답받은 값들을 Header컴포넌트 페이지에 부쳐서 GNB카테고리 노출
  • 작업: store vuex에서 데이터 상태관리
  • 정리: vuex속성, getters

actions

export const actions = {
	async getGndList ({commit}) {
		const {data} = await this.$axios.request({
			url: setUrl('list'), ///svc/gnb/list
			methods:'get', 
		})
		if (data.result === '200' && data.resultMessage === 'SUCCESS') {
      		commit('SET_GNB_LIST', data.items)
        } else {
        	return this.$modal.alert({ message: data.resultMessage })
    	}
	}
}

actions > getGnbList을 api와 연동해서 값을 받아 결과가 성공인 경우 commit()을 통해 mutations를 호출한다.

API호출 결과값

JSON형태의 응답결과로 카테고리에서 label를 통해 화면에 노출시킬려는데 label값들이 서로 다른 것을 볼 수 있다. (getters에서 데이터 값 가공)

"result": "200",
    "resultMessage": "SUCCESS",
    "locale": "en_US",
    "totalCount": 10,
    "resultCount": 10,
    "items": [
        {
            "id": "852140529",
            "label": "가전",
            "name": "가전",
            "gnbType": {
                "value": "url",
                "label": "페이지URL"
            },
            "url": null
        },
        {
            "id": "1573738589",
            "label": "{\"ko\":\"카테고리\",\"en\":\"Product\"}",
            "name": "{\"ko\":\"카테고리\",\"en\":\"Product\"}",
            "gnbType": null,
            "url": null
        },
        {
            "id": "686402180",
            "label": "{\"ko\":\"패밀리세일\",\"en\":\"Best\"}",
            "name": "{\"ko\":\"패밀리세일\",\"en\":\"Best\"}",
            "gnbType": null,
            "url": "/familySale"
        },
        {
            "id": "1004768442",
            "label": "{\"ko\":\"식품관\",\"en\":\"Exhibitions\"}",
            "name": "{\"ko\":\"식품관\",\"en\":\"Exhibitions\"}",
            "gnbType": null,
            "url": "/\bfood"
        },
        {
            "id": "1541685323",
            "label": "베스트",
            "name": "베스트",
            "gnbType": null,
            "url": null
        },
        {
            "id": "296754970",
            "label": "{\"en\":\"About US\",\"ko\":\"신상품\"}",
            "name": "{\"en\":\"About US\",\"ko\":\"신상품\"}",
            "gnbType": null,
            "url": "/new"
        },
        {
            "id": "16283626",
            "label": "{\"ko\":\"한정특가\"}",
            "name": "{\"ko\":\"한정특가\"}",
            "gnbType": null,
            "url": "/limited"
        },
        {
            "id": "178866230",
            "label": "{\"ko\":\"기획전\"}",
            "name": "{\"ko\":\"기획전\"}",
            "gnbType": null,
            "url": "/exhibition"
        },
        {
            "id": "167112478",
            "label": "{\"ko\":\"단체선물\"}",
            "name": "{\"ko\":\"단체선물\"}",
            "gnbType": null,
            "url": "/gift"
        },
        {
            "id": "1275124970",
            "label": "{\"ko\":\"이벤트\"}",
            "name": "{\"ko\":\"이벤트\"}",
            "gnbType": null,
            "url": "/event"
        }
    ]
}

mutations

export const mutations = {
  SET_GNB_LIST (state, data) {
    state.gnbList = data
  },
}

위에서 성공인 경우 actions가 호출한 mutations > 'SET_GNB_LIST'에
성공한 결과값을 state.gnbList로 값을 넣어준다.

state

export const state = () => ({
  gnbList: [],
  gnbListKo: [],
})

공통으로 사용할 값들을 정의하는 곳

getters

export const getters = {
  gnbList: s => s.gnbList,
  gnbListKo: (s) => {
    const list = _.cloneDeep(s.gnbList)
    list.forEach((items) => {
      try {
        if (typeof (JSON.parse(items.label)) === 'object') {
          // GNB 리스트api결과값 임시로 ko분리
          items.label = JSON.parse(items.label).ko
        }
      } catch (err) {
      }
    })
    return list
  },
}

getters에서 값을 가공해서 사용하는 이유!

값에 대해서 가공이 필요할때 컴포넌트에서 computed를 통해 작업을 할 수 있다. 그러나 또 다른 페이지에서도 동일한 데이터값이 필요하다면 동일한 작업을 컴포넌트 > computed에서 해야한다.
그렇게 코드는 중복이되고, 유지보수또한 힘들어지게 된다.

vuex getters는 computed처럼 state값이 변경될 때 상태를 계산할 수 있는 속성이므로 상황에 맞춰 잘 사용하자! computed 보러가기

profile
물음표 살인마

0개의 댓글

관련 채용 정보