728x90
반응형
SMALL

안녕하세요!

프뚜(프로그래머 뚜)입니다!

 

[개발 환경]

 - OS: windows 10 64bit

 - git: 2.37.1.windows.1

 - nodejs: v16.16.0

 - npm: 8.15.0

 - yarn: 1.22.19

 - @vue/cli(vue3): 5.0.8

 

vue를 사용하다보면 state를 저장하거나 전역변수처럼 어디서든 사용해야할 때가 있습니다.

예를 들어 부모와 자식 관계가 깊은 상황에 부모의 값을 변경하기 위해선 emit으로 많은 자식을 거쳐야합니다.

이럴 때 사용하는 vuex에 대해서 포스팅해보겠습니다. (링크)

 

mutations은 state의 값을 변경할 때 쓰이며, actions은 method로 사용됩니다.

 

 

1. mutations 사용하기

import { createStore } from 'vuex';

export default createStore({
  state: {
    name: '',
    job: ''
  },

  mutations: {
    SET_NAME(state, param) {
      state.name = param;
    }
  },
});

 

# store.commit(mutations name, param)으로 state 값을 변경시킴
<template>
  Main입니다.
</template>

<script setup>
// 2022.08.21[프뚜]: 01. vuex의 useStore를 import
import { useStore } from 'vuex';

// 2022.08.21[프뚜]: 02. userStore의 값을 store로 받음
const store = useStore();

// 2022.08.21[프뚜]: 03. state(mutations) 값 변경
store.commit('SET_NAME', '프뚜');

// 2022.08.21[프뚜]: 04. state 출력
console.log(store.state.name);
</script>

mutations에 선언된 SET_NAME을 통해 name state를 변경했습니다.

 

 

2. actions 사용하기

# actions에서 값을 바로 바꿀 수 없기 때문에 mutations을 이용함
import { createStore } from 'vuex';

export default createStore({
  state: {
    name: '',
    job: ''
  },

  mutations: {
    SET_NAME(state, param) {
      state.name = param;
    },
    SET_JOB(state, param) {
      state.job = param;
    },
  },

  actions: {
    setNameAndJob({ commit }) {
      commit('SET_NAME', '프뚜');
      commit('SET_JOB', '프로그래머');
    }
  }
});

 

# mutations은 commit을 통해 사용하지만 actions는 dispatch로 사용함
<template>
  Main입니다.
</template>

<script setup>
// 2022.08.21[프뚜]: 01. vuex의 useStore를 import
import { useStore } from 'vuex';

// 2022.08.21[프뚜]: 02. userStore의 값을 store로 받음
const store = useStore();

// 2022.08.21[프뚜]: 03. state(actions) 값 변경
store.dispatch('setNameAndJob');

// 2022.08.21[프뚜]: 04. state 출력
console.log(store.state.name);
console.log(store.state.job);
</script>

mutations은 commit을 통해 사용하지만 actions는 dispatch로 사용합니다.

 

 

해당 프로젝트는 gitlab에 제공되고 있습니다. (포스팅 제목과 Git History는 1:1 매칭입니다.)
https://github.com/JeongSeongSoo/vue-tistory

 

GitHub - JeongSeongSoo/vue-tistory

Contribute to JeongSeongSoo/vue-tistory development by creating an account on GitHub.

github.com


궁금하신 부분 또는 문제가 생긴 부분에 대해서 댓글 남겨주시면 빠르고 정확한 답변드리겠습니다.

728x90
반응형
LIST
프뚜