๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿ’ก์›น ํ”„๋กœ์ ํŠธ/(ํ”„๋ก ํŠธ์—”๋“œ) ๋งˆ์ผ“์ปฌ๋ฆฌ - ํด๋ก ์ฝ”๋”ฉ

vuex ๋ฐ์ดํ„ฐ ์ „๋‹ฌ(์ƒ์œ„->ํ•˜์œ„)

์ฐธ๊ณ ํ•œ ๊ฒŒ์‹œ๋ฌผ >

https://xn--xy1bk56a.run/vuex/3-cart/

https://joshua1988.github.io/web-development/vuejs/vuex-start/

 

1. vuex ์„ค์น˜, ์„ค์ •

1) vuex ์„ค์น˜

NPM ์„ค์น˜ ๋ช…๋ น์„ ์‚ฌ์šฉํ•˜์—ฌ Vuex ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ํ”„๋กœ์ ํŠธ์— ์„ค์น˜ํ•œ๋‹ค.

npm install vuex

 

2) vuex ํ”Œ๋Ÿฌ๊ทธ์ธ ๋“ฑ๋ก

ํ”„๋กœ์ ํŠธ ๋ฃจํŠธ ์œ„์น˜์— store/index.js ํŒŒ์ผ์„ ๋งŒ๋“  ํ›„, Vuex ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ Vue ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์˜ ํ”Œ๋Ÿฌ๊ทธ์ธ์œผ๋กœ ๋“ฑ๋กํ•˜๋Š” ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•œ๋‹ค. ๊ทธ๋ฆฌ๊ณ  Vuex๋ฅผ ํ†ตํ•ด Store ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๊ตฌ๋ฌธ์„ ์„ค์ •ํ•œ๋‹ค.

// store/index.js

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

Vue.use(Vuex)

export const store = new Vuex.Store({
  // ์Šคํ† ์–ด ๊ฐ์ฒด ์˜ต์…˜ ์„ค์ •
})

 

- vuex ์†์„ฑ ์„ค์ •

์Šคํ† ์–ด ๊ฐ์ฒด ์ƒ์„ฑ ๊ณผ์ •์—์„œ ์„ค์ • ๊ฐ€๋Šฅํ•œ ์†์„ฑ์€ ํ•„์š”์— ๋”ฐ๋ผ ์„ ํƒ์ ์œผ๋กœ ์ถ”๊ฐ€ํ•  ์ˆ˜ ์žˆ๋‹ค.

const store = new Vuex.Store({
  state: { ... },     // = ๋ฐ์ดํ„ฐ (data)
  getters: { ... },   // = ๊ณ„์‚ฐ๋œ ์†์„ฑ (computed Properties)
  mutations: { ... }, // = ๋ฐ์ดํ„ฐ ๋ณ€๊ฒฝ (sync)
  actions: { ... }    // = ๋ฉ”์„œ๋“œ (methods, async)
})

 

3) ํ”„๋กœ์ ํŠธ์˜ main.js์— store.js ๋“ฑ๋ก

// main.js
import Vue from "vue";
import App from "./App.vue";
// store.js๋ฅผ ๋ถˆ๋Ÿฌ์˜ค๋Š” ์ฝ”๋“œ
import { store } from "./store";

new Vue({
  el: "#app",
  // ๋ทฐ ์ธ์Šคํ„ด์Šค์˜ store ์†์„ฑ์— ์—ฐ๊ฒฐ
  store: store,
  render: h => h(App)
});

 

2. ์ƒ์œ„ ์ปดํฌ๋„ŒํŠธ์—์„œ ํ•˜์œ„ ์ปดํฌ๋„ŒํŠธ๋กœ ๋ฐ์ดํ„ฐ ์ „๋‹ฌ

1) store.js์— state ์ถ”๊ฐ€

export const store = new Vuex.Store({
  // counter๋ผ๋Š” state ์†์„ฑ์„ ์ถ”๊ฐ€
  state: {
    counter: 0
  }
});

 

2) ์ƒ์œ„ ์ปดํฌ๋„ŒํŠธ์—์„œ state์— ์ ‘๊ทผ

<!-- App.vue(Parent) -->
</template>
  <div id="app">
    Parent counter : {{ $store.state.counter }} <br />
    <button @click="addCounter">+</button>
    <button @click="subCounter">-</button>

    <!-- ๊ธฐ์กด ์ฝ”๋“œ -->
    <!-- <child v-bind:num="counter"></child> -->
    <child></child>
  </div>
</template>

<script>
import Child from "./Child.vue";

export default {
  components: {
    child: Child
  },
  methods: {
    addCounter() {
      this.$store.state.counter++;
    },
    subCounter() {
      this.$store.state.counter--;
    }
  }
};
</script>

 

3) ํ•˜์œ„ ์ปดํฌ๋„ŒํŠธ์—์„œ state์— ์ ‘๊ทผ

<template>
  <div>
    Child counter : {{ $store.state.counter }}
    <button>+</button>
    <button>-</button>
  </div>
</template>