Vuex (1) createStore

서영·2021년 10월 2일
0

Vue

목록 보기
1/6

  • 다음과 같이 버튼을 눌렀을 때 1씩 Add하고 싶다.

  • vuex의 store 기능을 이용하기 위해 main.js에서 createStore 클래스를 import 해준다.

import { createApp } from 'vue';
import { createStore } from 'vuex';

import App from './App.vue';

const store = createStore({});

const app = createApp(App);

app.mount('#app');
  • createStore()는 object를 가진다.
const store = createStore({
    state() {
        return {   };
    }
});
  • createStore는 state()라는 메소드를 가지고, 이는 object를 return한다.
const store = createStore({
    state() {
        return {
            counter: 0
        };
    }
});
  • 다음과 같이 counter 변수를 선언하면 전역에서 접근이 가능한 state가 만들어짐.

  • App.vue로 돌아와서
<template>
  <base-container title="Vuex">
    <h3>{{$store.state.counter}}</h3>
    <button @click="addOne">Add 1</button>
  </base-container>
</template>

다음과 같이 $ 사인을 붙인 store의 state를 통해 변수에 접근할 수 있다.

methods:{
    addOne(){
      this.$store.state.counter++;
    }
  },
computed:{
    counter(){
      return this.$store.state.counter;
    }
  }
  • 메소드로 쉽게 할 수 있지만 html을 더 깔끔하게 해주고 싶다면 computed로 빼서 counter 만 써줘도 된다.

  • count를 해주는 기능을 components로 따로 빼준다.

TheCounter.vue에 counter를 출력하는 html과 counter를 반환하는 computed를 작성한다.

<template>
    <h3>{{counter}}</h3>
</template>

<script>
export default {
    computed:{
        counter(){
            return this.$store.state.counter;
        }
    }
}
</script>

<style>

</style>

App.vue에서 해당 컴포넌트를 import해주고 html로 써주기만 하면 됨

장점) props를 일일이 넘길 필요 없이 global하게 state를 사용할 수 있다.

  • App.vue 전체 코드
<template>
      <base-container title="Vuex">
        <the-counter></the-counter>
        <button @click="addOne">Add 1</button>
      </base-container>
    </template>
    
    <script>
    import BaseContainer from './components/BaseContainer.vue';
    import TheCounter from './components/TheCounter.vue';
    
    export default {
      components: {
        BaseContainer,
        TheCounter,
      },
      computed:{
        counter(){
          return this.$store.state.counter;
        }
      },
      methods:{
        addOne(){
          this.$store.state.counter++;
        }
      }
    };
    </script>
    
    <style>
    * {
      box-sizing: border-box;
    }
    
    html {
      font-family: sans-serif;
    }
    
    body {
      margin: 0;
    }
    </style>
profile
꾸준히 공부하기

0개의 댓글