Vue vuex

박경준·2021년 11월 5일
0

vue beginner

목록 보기
18/18

모든 컴포넌트에 대한 중앙 집중식 데이터 저장소 역할을 하며 예측가능한 방식으로 상태를 변경할 수 있다.

// /src/store
import { createStore } from "vuex";

const store = createStore({
  state() {
    return {
      count: 0,
      cart: [
        {
          product_id: 1,
          product_name: "아이폰 거치대",
          category: "A",
        },
      ],
    };
  },
  getters: {
    cartCount: (state) => {
      return state.cart.length;
    },
  },
  mutations: {
    increment(state, payload) {
      state.count += payload;
    },
  },
  actions: {
    increment(context, payload) {
      //비동기 처리 로직 수행 가능
      context.commit("increment", payload);
    },
  },
});

export default store;
// /views/StoreAccess
<template>
  <p>Count : {{ count }}</p>
  <p>cartCount : {{ cartCount }}</p>
  <button type="button" @click="increment">Increment</button>
</template>
<script>
export default {
  computed: {
    count() {
      return this.$store.state.count;
    },
    cartCount() {
      return this.$store.getters.cartCount;
    },
  },
  methods: {
    increment() {
      // this.$store.commit("increment", 1);
      this.$store.dispatch("increment", 1);
    },
  },
};
</script>

state - 프로젝트 전체에서 공통으로 사용할 변수를 정의. state에 정의된 변수는 computed 속성을 이용해서 변경사항을 항상 추적할 수 있음.

computed: {
  count() {
    return this.$store.state.count;
  }
}

getters - state에 저장된 변수를 getters로 쉽게 가져올 수 있다. state 값을 그대로 가져올때와 다른 점은 연산을 통해 값을 변경할 수도 있다.

computed: {
  cartCount() {
    return this.$store.getters.cartCount;
  }
}

mutations - state에 정의된 변수를 직접 변경하는 것을 허용하지 않는다. 때문에 mutations를 이용해 state를 변경한다. mutations는 동기 처리된다. mutations에 정의된 함수를 commit을 통해 호출한다.

methods: {
  increment() {
    this.$store.commit('increment');
  }
}

actions - mutations와 달리 비동기 처리된다. store에서 비동기 처리 로직을 관리할 수 있게 해준다.

actions: {
  increment(context) {
    context.commit('increment');
  }
}
profile
빠굥

0개의 댓글