vuex

채윤·2022년 6월 19일
0

store.js

//모든 컴포넌트에서 사용할 중앙저장소
import { createStore } from "vuex";

const store = createStore({
  state() {
    //관리하고 싶은 데이터를 선언해서 상태관리
    return {
      count: 0,
      cart: [{ product_id: 1, product_name: "아이폰 거치대", category: "A" }],
      cart: [{ product_id: 2, product_name: "블루투스 마우스", category: "B" }],
    };
  },
  mutations: {
    //mutations에 메소드를 통해서만 state값을 변경할 수 있다.
    increment(state) {
      state.count = state.count + 1;
    },
  },
  getters: {
    //state의 값을 가지고 특정 로직을 실행시켜 컴포넌트에서 getter를 사용할 수 있다.
    cartCount: (state) => {
      return state.cart.length;
    },
    productACount: (state) => {
      return state.cart.filter((p) => p.category == "A").length;
    },
  },
});

export default store;
  • store는 모든 컴포넌트에서 사용할 중앙저장소이다.
  • state - 관리하고 싶은 데이터를 선언한다.
  • mutations - mutations에서 선언된 메소드를 통해서만 state값을 변경할 수 있다.
  • getters - state의 값을 가지고 특정 로직을 실행시켜 컴포넌트에서 getter를 사용할 수 있다.

main.js

import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";

createApp(App).use(store).use(router).mount("#app");

StoreAccess.vue

<template>
  <div>
    <h1>Cart: {{ cartCount }}</h1>
    <h1>Cart-Product A: {{ cartCount }}</h1>
    <h2>Count: {{ count }}</h2>
    <button type="button" @click="increment"></button>
  </div>
</template>
<script>
export default {
  computed: {
    count() {
      return this.$store.state.count; //store count감시해서 변경사항 적용
    },
    cartCount() {
      return this.$store.getters.cartCount;
    },
    productACount() {
      return this.$store.getters.productACount;
    },
  },
  methods: {
    increment() {
      this.$store.commit("increment");
      //mutations에 있는 함수를 호출하기 위해서는 commit 사용해야함
    },
  },
};
</script>
  • mutations에서 함수를 정의하고 실제 컴포넌트에서는 commit을 사용해 관리하도록 되어 있다.
  • 사용자 로그인 시점에 로그인 정보를 넣어서 사용할 수 있다.
  • 로그인 여부를 알아야 하는 컴포넌트에서는 computed를 통해 유저 정보 여부를 판단한다.
  • 쇼핑앱의 경우 장바구니(장바구니 변경사항을 실시간 반영해야 할 경우)
profile
프론트엔드 개발자

0개의 댓글