공부/Vue.js

[Vue.js] Vuex란? / Vuex 예제

bumcrush 2019. 7. 16. 15:49
반응형

Vuex란?

- vuex는 상태관리를 위한 패턴이자 라이브러리

 

Vuex 왜 사용?

- vue.js는 데이터 통신을 할 때 상-하위 관계가 아니면 데이터 통신이 어려운데,

- vuex는 데이터를 store.js라는 한 곳에 모아서 꺼내 쓰게 하여, 컴포넌트 간의 통신이나 데이터 전달을 좀 더 편하게 관리해준다.

 

store.js

  • state : 데이터
  • getter : state를 화면에 바인딩 / computed에 등록
  • mutation : state값을 변경(=setter) / methods에 등록 / 동기
  • actions : 이벤트처리, http통신 처리등 언제 결과를 받아올지 예측 할 수 없을 경우에 사용 / methods에 등록 / 비동기

methods와 computed 차이점

  • methods : 이 안에 들어있는 함수들이 모든 상황에서 재실행 (새롭게 다시 계산) => 모두 methods에 넣으면 성능 저하될수도 있음!
  • computed : 참고하고 있는 값의 변경에만 재실행

vue.js / vuex / vuex 예제 / vuex 란

vuex 예제

(* 참고 블로그 : https://joshua1988.github.io/web-development/vuejs/vuex-start/#%EB%93%A4%EC%96%B4%EA%B0%80%EB%A9%B0)

 

1. 프로젝트 생성 및 구조

- cmd창 열어서

> vue  create vuex-test

 

프로젝트 구조

2. vuex 설치

- 프로젝트 안에서 

> npm install vuex --save

 

3. src/main.js

- vuex 등록 

import Vue from 'vue'
import App from './App.vue'
//store.js를 불러와
import {store} from './store'


Vue.config.productionTip = false

new Vue({
  render: h => h(App),

  //Vue 인스턴스에 등록한다.
  store
}).$mount('#app')

 

4. src/store.js 

- store.js 만들어서 vuex 자원(?) 등록

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

export const store = new Vuex.Store({
    // counter 라는 state 속성을 추가
    state: {
        counter: 0
    },
    getters: {
        getCounter(state){
            return state.counter;
        }
    },
    mutations: {
        addCounter(state){
            return state.counter++;
        },
        subCounter(state){
            return state.counter--;
        }
    },
    actions : {
        addCounter(context) {
            return context.commit('addCounter');
        }
    }
});

vue.js / vuex / vuex 예제 / vuex 란

 

5. src/App.vue

<template>
  <div id="app">
    Parent counter : {{ parentCounter }} <br>
    
    <button @click="addCounter">+</button>
    <button @click="subCounter">-</button>

    <!-- Child 컴포넌트를 등록하고 counter 데이터 속성을 props 로 전달한다. -->
    <!--<child v-bind:passedCounter="counter"></child> -->

    <child></child>
  </div>
</template>

<script>
import Child from './components/Child.vue'
import { mapGetters, mapMutations , mapActions } from 'vuex'

export default {
  methods: {
     ...mapMutations({
       //addCounter:'addCounter'  ,
       subCounter:'subCounter'
     }),

    ...mapActions({
      addCounter:'addCounter'
    })
     
  },
  computed: {
    ...mapGetters({
       parentCounter : 'getCounter'
    })

  },
  components: {
    // Child 컴포넌트를 하위 컴포넌트로 등록
    'child': Child
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

 

 

6. src/components/Child.vue

<template>
    <div>
        <hr>
        Child counter : {{ childCounter }} <br>
    </div>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  // Parent 에서 넘겨준 counter 속성을 passedCounter 로 받음
  //props: ['passedCounter']
    computed:{
     ...mapGetters({
      childCounter : 'getCounter'
      })
    },
    
}
</script>

vue.js / vuex / vuex 예제 / vuex 란

7. 실행 및 결과 

> npm run serve

 

 


소스 다운로드

https://github.com/sbomhoo/vuex-test

 

sbomhoo/vuex-test

Vuex 예제. Contribute to sbomhoo/vuex-test development by creating an account on GitHub.

github.com

 

반응형