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에 대해서 포스팅해보겠습니다.

 

 

1. vuex 설치하기 (링크)

npm install vuex@next --save

 

 

2. store 폴더 및 store.js 생성하기

# vue store 관련된 파일은 여기에서 관리함
vue-tistory/src/store/store.js

 

 

3. vuex store 연결하기

# store.js
import { createStore } from 'vuex';

export default createStore({
  state: {

  }
});

 

# main.js에 store 사용을 연결하기
...
import store from '@/store/store.js';

...
app.use(stroe);
...

 

 

4. store에 값을 추가 후 확인하기

# store.js에 name, job 추가하기
...
  state: {
    name: '',
    job: ''
  }
...

 

# Main.vue에서 store.js 값 확인하기
<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 출력
console.log(store.state);
</script>

 

name과 job이 출력됨을 확인할 수 있습니다.

 

 

해당 프로젝트는 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
프뚜