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;
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>