vue.js

[vue.js] Vuex

망고고래 2025. 1. 9. 21:55

1. Vuex

vue.js 애플리케이션을 위한 상태관리 패턴 + 라이브러리

모든 컴포넌트에 대한 중앙집중식 저장소 역할을 함

 

2. vuex 설치

npm install vuex@next --save

 

 

3. 시작하기

저장소의 상태를 직접 변경할 수 없음

명시적인 커밋을 통해서만 변경할 수 있음

 

스토어 작성

import {createStore} from 'vuex'

const store = createStore({
    state(){
        return {
            count: 0
        }
    },
    mutations: {
        increment(state){
            state.count++
        }
    }
})

export default store;

 

컴포넌트에서 스토어에 접근

<template>
    <p>Count: {{count}}</p>
    <button type="button" @click="increment">Increment</button>
</template>
<script>
    export default{
        computed: {
            count(){
                return this.$store.state.count;
            }
        },
        methods: {
            increment(){
                this.$store.commit('increment');
            }
        }
    }
</script>

 

 

 

 

4. state

프로젝트 전체에서 공통으로 사용하는 변수 정의

computed: {
    count(){
        return this.$store.state.count;
    }
}

 

 

5. getters

state에 저장된 변수의 값을 가져옴

getters: {
    count: (state) => {
        return state.cart.length;
    }
},
mutations: {
    increment(state){
        state.count++
    }
}

 

 

6. mutations

state에 정의된 변수를 변경함

동기 처리

 

mutations에 정의된 함수를 commit을 통해 호출

methods: {
    increment(){
        this.$store.commit('increment');
    }
}

 

 

7. Actions

mutations에 정의된 함수를 실행시킬 수 있음

- 여러 개의 mutations 실행 가능

- 비동기 작업 가능

actions: {
    increment(context){
        context.commit('increment')
    }
}

 

 

 

8. 예제

import{
    createStore
} from 'vuex'

import persistedstate from 'vuex-persistedstate';

const store = createStore({
    state(){
        return{
            user: {}
        }
    },
    mutations: {
        user(state, data){
          state.user = data;
        }
    },
    plugins: [
        persistedstate({
            paths: ['user']
        })
    ]
});

export default store;