Skip to content
Search

Vuex

lastmod 2022-05-06created 2020-06-1514 edits

Vuex is a state management pattern + library for Vue.js applications. It serves as a centralized store for all the components in an application and lets you change state in a predictable way. It also integrates with Vue's official devtools extension to provide advanced features such as zero-setup debugging and state snapshot export/import.

Architecture

This single diagram explains everything.

Vuex_-_architecture_diagram.png

Global access

this.$store

Persist, and how to create a store

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

The following is printed in the browser error log:

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."

Like this:

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

You must not obtain a store object and modify it directly.

See also

Favorite site

Tutorials

author Zer0 sitemap