공부용

[vue.js] 5. vuex 본문

공부용/vue.js

[vue.js] 5. vuex

고딕짱! 2022. 2. 21. 14:01

 

0. vuex

vuex는 vue.js 애플리케이션을 위한 상태 관리 패턴 + 라이브러리이다. 상태가 예측 가능한 방식으로만 변경될 수 있도록 하는 규칙과 함께 응용 프로그램의 모든 구성 요소에 대한 중앙 집중식 저장소 역할

 

// 공식 url

https://vuex.vuejs.org/

 

What is Vuex? | Vuex

What is Vuex? NOTE This is the docs for Vuex 4, which works with Vue 3. If you're looking for docs for Vuex 3, which works with Vue 2, please check it out here. Vuex is a state management pattern + library for Vue.js applications. It serves as a centralize

vuex.vuejs.org

 

1. 설치

npm install vuex@next --save

 

 

2. 기본세팅

2-1 ./src/assets/store.js

import { createStore } from "vuex";

export default createStore({
  state: {
    counter: 10
  }
});

 

2-2

main.js

import store from "./assets/store.js" // 스토어 추가

const app = createApp(App);
app.use(store);

app.mount('#app');

 

2-3

./src/view/vuex.vue

<template>
  <div>
     counter : {{ counter }}
    <br>
    <button @click="addCounter">+</button>
    <button @click="subCounter">-</button>
  </div>
</template>

<script>
export default {
  data () {
    return {
      counter: 0
    }
  },
  created() {
    this.counter = this.$store.state.counter;
  }
};
</script>

this.$store로 변수를 공유할 수 있다.

 

 

3. getters 와 mutations

위와 같이 상태를 관리하면 무분별(?)하게 된다.

그래서 getters와 mutation를 추가하여 적절하게 관리한다

 

./src/assets/store.js

import { createStore } from "vuex";

export default createStore({
  state: {
    counter: 10
  },
  getters: { // 상태를 가져오는 getters
    getCounter: function(state) {
      return state.counter;
    }
  },
  mutations: { // 상태 동작을 하는 mutations 
    addCounter: function(state) {
      return state.counter++;
    },
    subCounter: function(state) {
      return state.counter--;
    }
  }
});

 

./src/view/vuex.vue

<template>
  <div>
     counter : {{ counter }}
    <br>
    <button @click="addCounter">+</button>
    <button @click="subCounter">-</button>
  </div>
</template>

 

<script>
  export default {
    computed: {
      counter() {
        return this.$store.getters.getCounter;
      }
    },
    methods: {
      addCounter() {
        this.$store.commit('addCounter');
      },
      subCounter() {
        this.$store.commit('subCounter');
      }
    }
  };
</script>

 

 

this.$store.getters를 통해 getters 안에 function을 호출하고

this.$store.commit('function')을 호출해서 값을 조작한다.

 

'공부용 > vue.js' 카테고리의 다른 글

[vue.js] 7. axios  (0) 2022.02.22
[vue.js] 6. mixins  (0) 2022.02.21
[vue.js] 4. props와 emit  (0) 2022.02.21
[vue.js] 3-2 v-if 와 v-on  (0) 2022.02.16
[vue.js] 3-1. vue 템플릿 문법 및 v-for  (0) 2022.02.16
Comments