[vue-news] 스토어 구현 - Vuex 설치, Vuex 모듈화 및 state 적용

aranpark·2021년 10월 8일
0

vue-news

목록 보기
8/8

💻 Vuex 설치


컴포넌트 데이터 호출 방법인 api폴더에서 바로 꺼내와서 개발하는 것이 아니라 Vuex라는 상태관리 도구를 이용해서 컴포넌트 데이터를 호출해 볼 것
1. npm i vuex 설치

💻 Vuex 모듈화 및 state 적용


  1. /src/main.js에 Vuex import
import Vue from 'vue';
import App from './App.vue';
import { router } from './routes/index.js';
// Vuex 라이브러리 로딩
import Vuex from 'vuex';

Vue.config.productionTip = false

new Vuex.Store({
  state,
  getters,
  setters,
  mutations,
  actions 
})

new Vue({
  render: h => h(App),
  router,
}).$mount('#app')

위와 같은 store에 관한 코드가 커지면 main.js의 본질을 흐리게 된다.

  1. /src/store/index.js로 파일분리
import Vue from 'vue';
import Vuex from 'vuex';
import actions from './actions.js';
import mutations from './mutations.js';

Vue.use(Vuex);

// const : 인스턴스 담기
// export : 내보내기
export const store = new Vuex.Store({
    state: {
        news: [],
    }
  })
  
  1. /src/main.js에 store import
import Vue from 'vue';
import App from './App.vue';
import { router } from './routes/index.js';
import { store } from './store/index.js';

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
  router,
  store
}).$mount('#app')

확인 방법

0개의 댓글