본문 바로가기

개발

[Vue.js] vuex 상태관리 사용법

 

Vuex 구조 (공식문서 : vuex.vuejs.org/kr)

Vuex?

 컴포넌트의 depth가 깊어질수록 컴포넌트끼리 데이터를 전달하는게 쉽지않음. 따라서 하나의 저장소(store)에서 손쉽게 관리할 수 있도록 나온 vuejs 라이브러리다.

 

 

사용법

vuex 설치

npm install vuex --save

 


src/api/index.js

import axios from 'axios';

const config = {
    baseUrl: 'https://my-backand-server.com/api'
}

function fetchArticle() {
    return axios.get(`${config.baseUrl}/article`);
}

function fetchReply() {
    return axios.get(`${config.baseUrl}/reply`);
}

export {
    fetchArticle,
    fetchReply,
}

 

src/store/index.js

import Vue from 'vue';
import Vuex from 'vuex';
import { getArticle, getReply } from '../api/index.js';

Vue.use(Vuex);

export const store = new Vuex.Store({
    state: {
        article: [],
        articleReply: []
    },
    actions: {
       FETCH_ARTICLE(context) {
        getArticle()
        .then(response => {
            context.commit('SET_ARTICLE', response.data);
        })
        .catch(error => {
            console.log(error);
        });
      },
      FETCH_REPLY(context) {
          getReply()
          .then(response => {
              context.commit('SET_REPLY', response.data);
          })
          .catch(error => {
              console.log(error);
          });
      },
    },
    mutations: {
    	SET_ARTICLE(state, article) {
        	state.article = article;
    	},
        SET_ASKS(state, reply) {
            state.articleReply = reply;
        },
    }
})

 

ㄴ vuex 라이브러리 import

ㄴ state : vuex 저장소에서 관리할 데이터들

ㄴ actions : action에서는 API를 통해 데이터를 가져오는 작업만을 한다.

ㄴ mutations : actions에서 context.commit()을 하면 선언된 mutations에서 state에 값을 할당한다.

 

src/views/ArticleView.vue

<template>
  <div>
    <p v-for="item in articles" :key="item.id">
      <a :href="item.url">{{ item.title }}</a>
    </p>
  </div>
</template>

<script>
export default {
  computed: {
    articles() {
      // store내의 state 데이터까지 접근하는데 너무 변수가 길어짐. 따라서 컴포넌트에서 보기좋게 사용하기위해 computed에 선언
      return this.$store.state.article;
    }
  },
  created() {
    // vuex 저장소에 선언된 actions(FETCH_ARTICLE) 실행
    this.$store.dispatch('FETCH_ARTICLE');
  }
}
</script>

<style>

</style>