본문 바로가기
카테고리 없음

vuex(store) 구성

by step 1 2021. 9. 3.
반응형

vuex 설치: npm i vuex@next

공식 문서

https://next.vuex.vuejs.org/

 

What is Vuex? | Vuex

What is Vuex? NOTE This is the docs for Vuex 4, which works with Vue 3. If you're looking for docs for Vuex 3, which works with Vue 2, please check it out here. Vuex is a state management pattern + library for Vue.js applications. It serves as a centralize

next.vuex.vuejs.org

vue 3 버전은 한글지원이 안되기 때문에 vue 2 버전을 참고해서 사용하는 방법도 있다.

실제 기술적인 코드는 vue3 문서를 이용하고 개념적인 것만 vue 2버전 공식 문서를 참고하는게 좋을 거 같다.

 

특정한 폴더에 있는 index라는 파일을 가져올때는 파일 명을 생략해줄수 있다.

import store from './store'

라이브러리, 플러그인을 사용할 때에는 use 명령어를 이용하여 사용한다.

createApp(App)
.use(router)
.use(store)
.mount('#app')

 

코드 작성

index.js

import {createStore} from 'vuex'
import movie from './movie.js'
import about from './about'

export default createStore({
  modules: {
    movie,
    about
  }
})

movie.js

expect default {
  // module!
  namespaced: true,
  //data!
  state: () => ({
    movies: []
  }),
  // computed!
  getters: {
    // 실제 데이터를 계산해서 새로운 데이터 형식으로 반영할때 사용
    movieIds(state) {
      return state.movies.map(m => m.imdbID)
    }
  },
  // methods!
  // 변이: 관리하는 데이터를 변경시켜줄수 있다. 다른 메소드에서 변경할 수 없다.
  mutations: {
    resetMovies(state) {
      state.movies = []
    }
  },
  // 비동기로 동작한다.
  actions: {
    searchMovies() {
      
    }
  }
}

main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './routes/index.js'
import store from './store'

createApp(App)
.use(router)
.use(store)
.mount('#app')
반응형