[Vue.js 3] vuex 예제

2023. 10. 29. 14:24· FE/Vue.js
목차
  1. vuex?
  2. vuex 설치 및 설정
  3. vuex 사용
반응형

프로젝트로 배우는 Vue.js 3

이 포스팅에서 작성하는 내용은 프로젝트로 배우는 Vue.js 3 에서 발췌하였습니다.
https://inf.run/sxQT

 

프로젝트로 배우는 Vue.js 3 - 인프런 | 강의

Vue.js 3 사용 방법을 배우고 프로젝트에 적용을 하면서 익힐 수 있도록 도와드립니다., 최신 Vue 3로 만나는,쉽고 강력한 프론트엔드 개발 입문! 강의 소개 [사진] 인기 프론트엔드 프레임워크, Vue.j

www.inflearn.com


vuex?

  • state 관리 툴
  • state를 vuex라는 저장소에서 관리하여 다른 컴포넌트에서 간편하게 접근 가능
  • 즉, state를 다른 컴포넌트로 보내주거나 받을 필요 없이 단순하게 vuex 저장소에 들어가서 접근할 수 있는 툴

https://v3.vuex.vuejs.org/kr/

 

Vuex가 무엇인가요? | Vuex

Vuex가 무엇인가요? Vuex는 Vue.js 애플리케이션에 대한 상태 관리 패턴 + 라이브러리 입니다. 애플리케이션의 모든 컴포넌트에 대한 중앙 집중식 저장소 역할을 하며 예측 가능한 방식으로 상태를

v3.vuex.vuejs.org

 

vuex 설치 및 설정

npm or yarn 설치

npm install vuex --save
yarn add vuex

vuex 설정

  1. vue 디렉토리에 store 라는 디렉토리를 생성 후 그 안에 index.js 파일 생성
  2. index.js 파일에 아래와 같이 입력
  3. import { createStore } from 'vuex';
    
    export default createStore({
        state: {
        }
    });
  4. vue 디렉토리의 main.js 에 아래와 같이 store를 import, use
  5. ...
    import store from './store';
    
    createApp(App).use(store).use(router).mount('#app'); // .use(store) 추가

 

 

vuex 사용

- store/index.js 파일의 state에 사용할 변수 및 mutations, actions, getters 추가

import { createStore } from 'vuex';

export default createStore({
    state: {
        state1: '',
        state2: false
    }, 
    mutations: { // UPDATE 함수 정의
        UPDATE_STATE1 (state, payload) {
            state.state1 = payload;
        },
        UPDATE_STATE2 (state, payload) {
            state.state2 = payload;
        }
    },
    actions: { // UPDATE 함수를 조합해서 custom 함수 정의
        updateAllState({ commit }, state1, state2) {
            // mutations을 호출 시, commit 이용
            commit('UPDATE_STATE1', state1);
            commit('UPDATE_STATE2', state2);
    },
    getters: { // state를 가져오는 custome 함수 정ㅈ의
        getState1StartByHello (state) {
            return 'Hello!' + state.state1;
        }
    }
});

 

- 사용할 컴포넌트에서 useStore import 및 예제

<script>
...

import { computed } from 'vue';
import { useStore } from 'vuex';

export default {
    ...
    setup() {
        ...
        const store = useStore();
        // 값을 가져오기만 하고, 값이 변경된 경우에도 기존 값을 그대로 가짐
        const state1 = store.state.state1;
        const state2 = store.state.state2;

        console.log('----- 변경 전 -----');

        console.log(store.state.state1); // ''
        console.log(store.state.state2); // false

        // 변경을 감지해서 변경된 값을 가져오게 설정
        const computedState1 = computed(() => store.state.state1);
        const computedState2 = computed(() => store.state.state2);

        console.log(computedState1); // ''
        console.log(computedState2); // false

        // actions 함수를 호출 시, dispatch 이용 (store/index.js 정의)
        store.dispatch('updateAllState', 'test', true);

        console.log('----- 변경 후 -----');

        console.log(state1); // ''
        console.log(state2); // false

        console.log(computedState1); // 'test'
        console.log(computedState2); // true

        console.log('getters - getState1StartByHello');
        const hello = store.getters.getState1StartByHello;
        console.log(hello); // Hello!test
        ...
     }
}

 

 

- store/index.js 파일에 그룹별로 설정해보기 - modules

 

 

store/index.js

import { createStore } from 'vuex';

export default createStore({
    modules: {
        group1: {
            namespaced: true, // namespaced 를 true로 설정해야 group1에 접근 가능
            state: {
                state1: '',
                state2: false
            }, 
            mutations: { // UPDATE 함수 정의
                UPDATE_STATE1 (state, payload) {
                    state.state1 = payload;
                },
                UPDATE_STATE2 (state, payload) {
                    state.state2 = payload;
                }
            },
            actions: { // UPDATE 함수를 조합해서 custom 함수 정의
                updateAllState({ commit }, state1, state2) {        
                    // mutations을 호출 시, commit 이용
                    commit('UPDATE_STATE1', state1);
                    commit('UPDATE_STATE2', state2);
            },
            getters: { // state를 가져오는 custome 함수 정ㅈ의
                getState1StartByHello (state) {
                    return 'Hello!' + state.state1;
                }
            }
        }
    }
});

 

- 사용할 컴포넌트

<script>
...
import { computed } from 'vue';
import { useStore } from 'vuex';

export default {
    ...
    setup() {
        ...
        const store = useStore();

        // 변경을 감지해서 변경된 값을 가져오게 설정
        const computedState1 = computed(() => store.state.group1.state1);
        const computedState2 = computed(() => store.state.group1.state2);

        console.log(computedState1); // ''
        console.log(computedState2); // false

        // actions 함수를 호출 시, dispatch 이용 (store/index.js 정의)
        store.dispatch('group1/updateAllState', 'test', true);

        console.log('----- 변경 후 -----');

        console.log(computedState1); // 'test'
        console.log(computedState2); // true

        console.log('getters - getState1StartByHello');
        const hello = store.getters.['group1/getState1StartByHello'];
        console.log(hello); // Hello!test
        ...
     }
}
반응형

'FE > Vue.js' 카테고리의 다른 글

[Vue.js 3] Teleport, Slot, v-model binding, toRefs  (0) 2023.10.01
[Vue.js 3] Lifecycle Hooks, 함수 재사용  (0) 2023.09.10
[Vue.js 3] Router / Event Bubbling / 객체 비교  (0) 2023.07.30
[Vue.js 3] Computed, async / await, watchEffect, watch  (0) 2023.07.16
[Vue.js 3] v-bind / v-model, v-for, v-show / v-if, emit / props  (0) 2023.07.09
  1. vuex?
  2. vuex 설치 및 설정
  3. vuex 사용
'FE/Vue.js' 카테고리의 다른 글
  • [Vue.js 3] Teleport, Slot, v-model binding, toRefs
  • [Vue.js 3] Lifecycle Hooks, 함수 재사용
  • [Vue.js 3] Router / Event Bubbling / 객체 비교
  • [Vue.js 3] Computed, async / await, watchEffect, watch
멍목
멍목
개발 관련 새롭게 알게 된 지식이나 좋은 정보들을 메모하는 공간입니다.
반응형
멍목
김멍목의 개발블로그
멍목
전체
오늘
어제
  • 분류 전체보기 (514)
    • BE (190)
      • Spring (21)
      • Java (141)
      • Kotlin (6)
      • JPA (22)
    • FE (33)
      • Javascript (16)
      • Typescript (0)
      • React (5)
      • Vue.js (9)
      • JSP & JSTL (3)
    • DB (32)
      • Oracle (22)
      • MongoDB (10)
    • Algorithm (195)
    • Linux (8)
    • Git (6)
    • etc (42)
    • ---------------------------.. (0)
    • 회계 (4)
      • 전산회계 2급 (4)
    • 잡동사니 (2)

블로그 메뉴

  • 홈
  • 관리

공지사항

인기 글

태그

  • 더 자바 애플리케이션을 테스트하는 다양한 방법
  • Oracle
  • JPA
  • JPA 공부
  • 프로젝트로 배우는 Vue.js 3
  • 더 자바 Java 8
  • 알고리즘공부
  • 코테공부
  • java 8
  • 자기공부
  • vue3 공부
  • MongoDB 기초부터 실무까지
  • 자바 개발자를 위한 코틀린 입문
  • 자바공부
  • junit5
  • MongoDB with Node.js
  • Effective Java
  • 알고리즘 공부
  • 전산회계 2급 준비
  • Java to Kotlin
  • 코틀린
  • 자기개발
  • 자기 개발
  • 이펙티브 자바
  • 자바 공부
  • 이펙티브자바
  • MongoDB 공부
  • 자바 테스팅 프레임워크
  • 코테 공부
  • 자기 공부

최근 댓글

최근 글

hELLO · Designed By 정상우.v4.2.0
멍목
[Vue.js 3] vuex 예제
상단으로

티스토리툴바

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.