What is vuex?
Vuex is a state management pattern + library for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion. It integrates well with Vue's official devtools extension to provide advanced features such as zero-config time-travel debugging and state snapshot export/import.
What are vuex's main functionalities?
State Management
Vuex allows you to define a centralized state for your application and mutate this state in a controlled way using mutations.
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
}
});
store.commit('increment');
console.log(store.state.count); // 1
Getters
Getters are like computed properties for stores. They can be used to compute derived state based on store state and are cached.
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done);
}
}
});
console.log(store.getters.doneTodos); // [{ id: 1, text: '...', done: true }]
Actions
Actions are similar to mutations, but instead of mutating the state, actions commit mutations. Actions can contain arbitrary asynchronous operations.
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state, payload) {
state.count += payload.amount;
}
},
actions: {
incrementAsync({ commit }, payload) {
setTimeout(() => {
commit('increment', payload);
}, 1000);
}
}
});
store.dispatch('incrementAsync', { amount: 10 });
Modules
Vuex allows you to divide your store into modules. Each module can contain its own state, mutations, actions, getters, and even nested modules.
const moduleA = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
Other packages similar to vuex
redux
Redux is a predictable state container for JavaScript apps, often used with React but can be used with any other JavaScript framework or library. It is similar to Vuex but has a different ecosystem and middleware support.
mobx
MobX is a state management library that is not restricted to React like Redux and provides a more flexible approach to state management based on observable data structures.
ngxs
NGXS is a state management pattern + library for Angular applications. It provides a similar centralized state management system to Vuex but is designed specifically for Angular's ecosystem.
akita
Akita is a state management pattern + library for Angular and React. It focuses on simplicity and sets up a store for managing the state of your application with less boilerplate than Redux or NGXS.
Vuex 4
This is the Vue 3 compatible version of Vuex. The focus is compatibility, and it provides the exact same API as Vuex 3, so users can reuse their existing Vuex code for Vue 3.
Status: Alpha
All Vuex 3 feature works. There are a few breaking changes described in a later section, so please check them out. You can find basic usage with both option and composition API at example
folder.
Please note that it's still unstable, and there might be bugs. Please provide us feedback if you find anything. You may use vue-next-webpack-preview to test out Vue 3 with Vuex 4.
Breaking changes
Installation process has changed
To align with the new Vue 3 initialization process, the installation process of Vuex has changed as well.
You should use a new createStore
function to create a new store instance.
import { createStore } from 'vuex'
const store = createStore({
state () {
return {
count: 1
}
}
})
This is technically not a breaking change because you could still use new Store(...)
syntax. However, to align with Vue 3 and also with Vue Router Next, we recommend users to use createStore
function instead.
Then to install Vuex to Vue app instance, pass the store instance instead of Vuex.
import { createApp } from 'vue'
import store from './store'
import App from './APP.vue'
const app = createApp(App)
app.use(store)
app.mount('#app')
Typings for ComponentCustomProperties
Vuex 4 removes its global typings for this.$store
within Vue Component due to solving issue #994. When using TypeScript, you must provide your own augment declaration.
Please place the following code in your project to have this.$store
working.
declare module "@vue/runtime-core" {
interface State {
count: number
}
interface ComponentCustomProperties {
$store: Store<State>;
}
}
Known issues
- The code is kept as close to Vuex 3 code base as possible, and there're plenty of places where we should refactor. However, we are waiting for all of the test cases to pass before doing so (some tests require Vue 3 update).
- TypeScript support is not ready yet. Please use JS environment to test this for now.
TODOs as of 4.0.0-alpha.1
Add TypeScript supportMake all unit test workingRefactor the codebaseUpdate the build system to align with Vue 3- Update docs
4.0.0-beta.1 (2020-04-25)
Features
- Added TypeScript support.
Breaking Changes
Bundles are now aligned with Vue 3
The bundles are generated as below to align with Vue 3 bundles.
vuex.global(.prod).js
- For direct use via
<script src="...">
in the browser. Exposes the Vuex global. - Note that global builds are not UMD builds. They are built as IIFEs and is only meant for direct use via
<script src="...">
. - Contains hard-coded prod/dev branches, and the prod build is pre-minified. Use the
.prod.js
files for production.
vuex.esm-browser(.prod).js
- For usage via native ES modules imports (in browser via
<script type="module">
.
vuex.esm-bundler.js
- For use with bundlers like
webpack
, rollup
and parcel
. - Leaves prod/dev branches with
process.env.NODE_ENV
guards (must be replaced by bundler). - Does not ship minified builds (to be done together with the rest of the code after bundling).
vuex.cjs.js
- For use in Node.js server-side rendering via
require()
.
Typings for ComponentCustomProperties
Vuex 4 removes its global typings for this.$store
within Vue Component due to solving issue #994. When using TypeScript, you must provide your own augment declaration.
Please place the following code in your project to have this.$store
working.
// vuex-shim.d.ts
declare module "@vue/runtime-core" {
// Declare your own store states.
interface State {
count: number
}
interface ComponentCustomProperties {
$store: Store<State>;
}
}