ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Vuex] Getters
    IT&컴퓨터공학/Vue 2021. 3. 10. 10:58

    Getters

    앞에서 Vuex 의 property 중 state 와 mutations 에 대해 다뤄봤다.

    쉽게말하면 state 는 전역으로 사용될 데이터의 집합이고 mutations 는 이 state 의 값에 접근해서 값을 바꾸는 함수의 모음이다.

     

    그럼 Getters 란 무엇일까 ? 

    여러 컴포넌트에서 Vuex state 를 각자 참조하고 계산하면 효율이 떨어진다.

    때문에, state 에 기반한 별도의 값을 만들어 getters 내에 속성으로 저장(캐쉬) 해두고,

    이 getters 내에 저장된 속성을 참조해서 사용하게 한다.

    // store.js (Vuex)
    getters: {
      doubleCounter: function (state) {
        return state.counter * 2;
      }
    },
    
    // App.vue
    computed: {
      AppdoubleCounter() {
        return this.$store.getters.doubleCounter;
      }
    },
    
    // Child.vue
    computed: {
      ChilddoubleCounter() {
        return this.$store.getters.doubleCounter;
      }
    },

    외부에서 this.$store.getters 로 접근이 가능하다.

     

    mapGetters

    Vuex에 내장된 helper 함수, 위의 코드를 더 직관적으로 작성할 수 있다.

     

    //store/index.js
    
    import Vue from 'vue';
    import Vuex from 'vuex';
    Vue.use(Vuex);
    
    export default new Vuex.Store({
      state: {
        count:0,
      },
      getters:{
        GetCount(state){
          return state.count;
        }
      },
    });
    
    // logout.vue
    
    <template>
        <div>
            <p>
                counter : {{ LogoutGetCount }}
            </p>
        </div>
    </template>
    
    <script>
    import { mapGetters } from 'vuex'
    
    export default {
        computed: mapGetters({
            LogoutGetCount : 'GetCount' // GetCount 는 store/index.js 안에 getters 에 선언된 함수이름
        }),
    
    }
    </script>

    여기서 주의할 점은 위 방법은 컴포넌트 자체에서 사용할 computed 속성과 함께 사용할 수 없다는 점이다. 해결방안은 ES6 의 문법 ... 을 사용하면 된다.

     

    //logout.vue
    
    <template>
        <div>
            <p>
                counter : {{ GetCount }}
            </p>
        </div>
    </template>
    
    <script>
    import { mapGetters } from 'vuex'
    
    export default {
        computed: {
            ...mapGetters([
                'GetCount'
            ]),
            anotherFunction(){
                return 0;
            },
        }
    
    }
    </script>

     

    Getter vs Mutations

     

    Mutations 는 Getter 와 다르게 

    1. Getter는 state 를 캐싱해두고 바로바로 꺼내올때 사용하고, Mutations 은 state 를 직접  변경할때 사용한다. 
    2. Getter는 computed 에 등록하며 Mutations 은 methods 에 등록한다.

     

    'IT&컴퓨터공학 > Vue' 카테고리의 다른 글

    [Vue.js] 6. 라우팅 - 동적 라우팅  (0) 2021.03.05
    [Vue.js] 6. 라우팅 - 중첩된 라우팅  (0) 2021.03.05
    [Vue.js] 5. 라우팅  (0) 2021.03.05
    [Vuex]1. Vuex 란 ?  (0) 2021.03.04
    [vue.js] 4. Directive 두번째 v-once  (0) 2021.03.03

    댓글

Designed by Tistory.