Skip to content

Vuex

Vuex는 Vue.js 애플리케이션에 대한 상태 관리 패턴 + 라이브러리 입니다. 애플리케이션의 모든 컴포넌트에 대한 중앙 집중식 저장소 역할을 하며 예측 가능한 방식으로 상태를 변경할 수 있습니다. 또한 Vue의 공식 devtools 확장 프로그램과 통합되어 설정 시간이 필요 없는 디버깅 및 상태 스냅 샷 내보내기/가져오기와 같은 고급 기능을 제공합니다.

Architecture

이 한 장의 그림으로 모든 것이 설명된다.

Vuex_-_architecture_diagram.png

Global access

this.$store

Persist 그리고, 스토어 생성 방법

main.js

import { sessionStore } from '@/store';
Vue.prototype.$store = sessionStore;

store.js

import Vue from "vue";
import Vuex from "vuex";
import { vuexSessionStorage, vuexLocalStorage } from "./persist";
import modules from "./modules";
import local_modules from "./local_modules";

Vue.use(Vuex);

export const sessionStore = new Vuex.Store({
  modules,
  strict: process.env.NODE_ENV !== "production",
  plugins: [vuexSessionStorage.plugin],
});

export const localStore = new Vuex.Store({
  modules: local_modules,
  strict: process.env.NODE_ENV !== "production",
  plugins: [vuexLocalStorage.plugin],
});

modules.js

const files = require.context('.', false, /\.js$/)
const modules = {}

files.keys().forEach(key => {
    if (key === './index.js') return
    modules[key.replace(/(\.\/|\.js)/g, '')] = files(key).default
})

export default modules

local_modules.js

const files = require.context('.', false, /\.js$/)
const local_modules = {}

files.keys().forEach(key => {
    if (key === './index.js') return
    local_modules[key.replace(/(\.\/|\.js)/g, '')] = files(key).default
})

export default local_modules

Troubleshooting

do not mutate vuex store state outside mutation handlers

브라우저 에러 로그로 다음이 출력된다:

vue.esm.js?a026:628 [Vue warn]: Error in callback for watcher "function () { return this._data.$$state }": "Error: [vuex] do not mutate vuex store state outside mutation handlers."

다음과 같이:

const user = this.$store.user;
// ....
user.extra[key] = value;

store 객체를 획득하고 바로 수정해선 안된다.

See also

Favorite site

Tutorials