
Vuex Vue2
- 26 installs
- 2 repo stars
- Updated July 29, 2026
- full-statck-skills/vue-skills
Guidance for Vuex 2.x state management in Vue 2, covering state, mutations, actions, getters, modules and plugins.
About
Provides Vuex 2.x guidance for managing application state in Vue 2 apps, including modules and plugins. A developer uses it when setting up or troubleshooting Vuex in a Vue 2 project.
- Covers state, getters, mutations and actions
- Includes modules, plugins and devtools usage
Vuex Vue2 by the numbers
- 26 all-time installs (skills.sh)
- Ranked #1,495 of 2,245 Frontend Development skills by installs in the Skillselion catalog
- Data as of Jul 30, 2026 (Skillselion catalog sync)
npx skills add https://github.com/full-statck-skills/vue-skills --skill vuex-vue2Add your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 26 |
|---|---|
| repo stars | ★ 2 |
| Last updated | July 29, 2026 |
| Repository | full-statck-skills/vue-skills ↗ |
What it does
Guidance for Vuex 2.x state management in Vue 2, covering state, mutations, actions, getters, modules and plugins.
Files
When to use this skill
Use this skill whenever the user wants to:
- Install and set up Vuex in a Vue 2 project
- Manage application state with Vuex
- Use Vuex store in Vue components
- Understand Vuex core concepts (state, getters, mutations, actions)
- Use Vuex modules for large applications
- Handle Vuex plugins and devtools
- Understand Vuex API and methods
- Troubleshoot Vuex issues
How to use this skill
This skill is organized to match the Vuex official documentation structure (https://vuex.vuejs.org/zh/, https://vuex.vuejs.org/zh/guide/, https://vuex.vuejs.org/zh/api/). When working with Vuex:
1. Identify the topic from the user's request:
- Installation/安装 →
examples/guide/installation.md - Quick Start/快速开始 →
examples/guide/quick-start.md - Core Concepts/核心概念 →
examples/core-concepts/ - Advanced/高级 →
examples/advanced/ - API/API 文档 →
api/
2. Load the appropriate example file from the examples/ directory:
Guide (使用指南):
examples/guide/intro.md- Introduction to Vuexexamples/guide/installation.md- Installation guideexamples/guide/quick-start.md- Quick start guideexamples/guide/what-is-vuex.md- What is Vuex
Core Concepts (核心概念):
examples/core-concepts/state.md- Stateexamples/core-concepts/getters.md- Gettersexamples/core-concepts/mutations.md- Mutationsexamples/core-concepts/actions.md- Actionsexamples/core-concepts/modules.md- Modules
Advanced (高级):
examples/advanced/plugins.md- Pluginsexamples/advanced/strict-mode.md- Strict modeexamples/advanced/form-handling.md- Form handlingexamples/advanced/testing.md- Testingexamples/advanced/hot-reload.md- Hot reload
3. Follow the specific instructions in that example file for syntax, structure, and best practices
Important Notes:
- Vuex is for Vue 2.x
- Store is the central state management
- State is reactive
- Mutations are synchronous
- Actions are asynchronous
- Each example file includes key concepts, code examples, and key points
4. Reference API documentation in the api/ directory when needed:
api/store-api.md- Store APIapi/state-api.md- State APIapi/getters-api.md- Getters APIapi/mutations-api.md- Mutations APIapi/actions-api.md- Actions APIapi/modules-api.md- Modules APIapi/plugins-api.md- Plugins API
5. Use templates from the templates/ directory:
templates/installation.md- Installation templatestemplates/store-setup.md- Store setup templatestemplates/component-usage.md- Component usage templates
1. Understanding Vuex
Vuex is a state management pattern and library for Vue.js applications. It serves as a centralized store for all the components in an application.
Key Concepts:
- Store: Centralized state container
- State: Application state (data)
- Getters: Computed properties for store
- Mutations: Synchronous state changes
- Actions: Asynchronous operations
- Modules: Store organization
2. Installation
Using npm:
npm install vuex@3Using yarn:
yarn add vuex@3Using CDN:
<script src="https://unpkg.com/vuex@3"></script>3. Basic Setup
// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
}
})
export default store// main.js
import Vue from 'vue'
import store from './store'
new Vue({
store,
render: h => h(App)
}).$mount('#app')Doc mapping (one-to-one with official documentation)
examples/guide/orexamples/getting-started/→ https://vuex.vuejs.org/zh/guide/api/→ https://vuex.vuejs.org/zh/api/
Examples and Templates
This skill includes detailed examples organized to match the official documentation structure. All examples are in the examples/ directory (see mapping above).
To use examples:
- Identify the topic from the user's request
- Load the appropriate example file from the mapping above
- Follow the instructions, syntax, and best practices in that file
- Adapt the code examples to your specific use case
To use templates:
- Reference templates in
templates/directory for common scaffolding - Adapt templates to your specific needs and coding style
API Reference
Detailed API documentation is available in the api/ directory, organized to match the official Vuex API documentation structure (https://vuex.vuejs.org/zh/api/):
Store API (api/store-api.md)
- Store constructor options
- Store instance properties
- Store instance methods
State API (api/state-api.md)
- State definition
- State access
- State reactivity
Getters API (api/getters-api.md)
- Getter definition
- Getter access
- Getter arguments
Mutations API (api/mutations-api.md)
- Mutation definition
- Mutation commit
- Mutation payload
Actions API (api/actions-api.md)
- Action definition
- Action dispatch
- Action context
Modules API (api/modules-api.md)
- Module definition
- Module namespacing
- Module registration
Plugins API (api/plugins-api.md)
- Plugin definition
- Plugin usage
- Built-in plugins
To use API reference: 1. Identify the API you need help with 2. Load the corresponding API file from the api/ directory 3. Find the API signature, parameters, return type, and examples 4. Reference the linked example files for detailed usage patterns 5. All API files include links to relevant example files in the examples/ directory
Best Practices
1. Use mutations for synchronous changes: Mutations must be synchronous 2. Use actions for async operations: Actions can contain async operations 3. Keep state normalized: Avoid nested state structures 4. Use modules for large apps: Organize store with modules 5. Use getters for computed state: Derive state with getters 6. Follow naming conventions: Use consistent naming patterns 7. Use TypeScript: Leverage TypeScript for type safety
Resources
- Official Documentation: https://vuex.vuejs.org/zh/
- Guide: https://vuex.vuejs.org/zh/guide/
- API Documentation: https://vuex.vuejs.org/zh/api/
- GitHub Repository: https://github.com/vuejs/vuex
Keywords
Vuex, vuex, Vue 2, state management, 状态管理, store, state, getters, mutations, actions, modules, 存储, 状态, 获取器, 变更, 动作, 模块, Vuex store, Vuex state, Vuex getters, Vuex mutations, Vuex actions, Vuex modules, Vuex plugins, centralized state, reactive state, synchronous mutations, asynchronous actions
能力边界
✅ 适用场景
- 当你需要使用此技能对应的技术栈时
- 当项目需要遵循最佳实践时
- 当需要快速上手或深入理解核心概念时
⚠️ 需要注意
- 复杂业务逻辑需要结合具体场景调整
- 性能优化需要根据实际数据量评估
❌ 不适用场景
- 不相关的技术栈或框架
- 需要完全自定义的特殊场景
常见陷阱 (Gotchas)
1. 版本兼容性:注意框架版本与依赖库的兼容性,不同版本 API 可能有差异 2. 配置文件格式:配置文件格式错误是最常见的问题,建议使用编辑器的语法检查 3. 环境变量:确保所有必要的环境变量已正确设置,敏感信息不要硬编码 4. 依赖冲突:多版本共存时注意依赖冲突,使用 lock 文件锁定版本 5. 性能陷阱:大数据量场景下注意性能优化,避免 N+1 查询等常见问题
使用流程
Step 1: 环境准备
确保开发环境已安装必要的依赖和工具。
Step 2: 配置初始化
根据项目需求进行基础配置。
Step 3: 核心功能使用
按照示例代码实现核心功能。
Step 4: 测试验证
运行测试确保功能正常。
Step 5: 部署上线
完成开发后进行部署和监控。
Actions API
API Reference
Vuex actions API.
Action Handler
actionHandler(context, payload)
- Action handler function
- Parameters:
context: Action context objectstate: Local stategetters: Local getterscommit: Commit functiondispatch: Dispatch functionrootState: Root staterootGetters: Root getterspayload: Action payload (optional)
Dispatch Method
store.dispatch(type, payload, options)
- Dispatch action
- Parameters:
type:string- Action typepayload:any- Action payload (optional)options:object- Options (optional)root:boolean- Dispatch to root (for namespaced modules)
Dispatch Examples
// String type
store.dispatch('increment')
// With payload
store.dispatch('fetchUser', userId)
// Object style
store.dispatch({
type: 'fetchUser',
userId: 1
})
// In namespaced module
store.dispatch('user/fetchUser', userId, { root: false })Action Context Destructuring
actions: {
async fetchData({ commit, state, dispatch, rootState }) {
// Use context properties
}
}Action Rules
- Actions can be asynchronous
- Actions commit mutations
- Actions can dispatch other actions
- Actions can access root state/getters
See also: examples/core-concepts/actions.md for detailed examples
Getters API
API Reference
Vuex getters API.
Getter Definition
getter(state, getters, rootState, rootGetters)
- Getter function
- Parameters:
state: Local state (module state if in module)getters: Local getters (module getters if in module)rootState: Root state (only in modules)rootGetters: Root getters (only in modules)
Getter Access
store.getters.getterName
- Access getter value
- Returns: Getter return value
Getter Examples
// Basic getter
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
}
// Getter with arguments (returns function)
getters: {
getTodoById: state => id => {
return state.todos.find(todo => todo.id === id)
}
}
// Getter accessing other getters
getters: {
doneTodos: state => state.todos.filter(todo => todo.done),
doneTodosCount: (state, getters) => getters.doneTodos.length
}Getter Access in Components
// Direct access
this.$store.getters.doneTodos
// With arguments
this.$store.getters.getTodoById(1)
// Using mapGetters
import { mapGetters } from 'vuex'
computed: {
...mapGetters(['doneTodos', 'doneTodosCount'])
}Getter Rules
- Getters are cached
- Getters are computed properties
- Getters can access other getters
- Getters receive state and getters as arguments
See also: examples/core-concepts/getters.md for detailed examples
Modules API
API Reference
Vuex modules API.
Module Definition
interface Module {
namespaced?: boolean
state?: Object | Function
getters?: Object
mutations?: Object
actions?: Object
modules?: Object
}Module Registration
Static Registration:
const store = new Vuex.Store({
modules: {
user: userModule,
products: productsModule
}
})Dynamic Registration:
store.registerModule('user', userModule)Module Namespacing
Namespaced Module:
const module = {
namespaced: true,
state: {},
getters: {},
mutations: {},
actions: {}
}Accessing Namespaced Module:
// State
store.state.moduleName.property
// Getters
store.getters['moduleName/getterName']
// Mutations
store.commit('moduleName/mutationName', payload)
// Actions
store.dispatch('moduleName/actionName', payload)Module Context
In namespaced modules, context provides:
state: Local module stategetters: Local module getterscommit: Local commit (namespaced)dispatch: Local dispatch (namespaced)rootState: Root staterootGetters: Root getters
Accessing Root
// Commit root mutation
commit('someMutation', null, { root: true })
// Dispatch root action
dispatch('someAction', null, { root: true })See also: examples/core-concepts/modules.md for detailed examples
Mutations API
API Reference
Vuex mutations API.
Mutation Handler
mutationHandler(state, payload)
- Mutation handler function
- Parameters:
state: Store state objectpayload: Mutation payload (optional)
Commit Method
store.commit(type, payload, options)
- Commit mutation
- Parameters:
type:string- Mutation typepayload:any- Mutation payload (optional)options:object- Options (optional)silent:boolean- Silent commit (no devtools)root:boolean- Commit to root (for namespaced modules)
Commit Examples
// String type
store.commit('increment')
// With payload
store.commit('increment', 10)
// Object style
store.commit({
type: 'increment',
amount: 10
})
// In namespaced module
store.commit('user/setName', 'John', { root: false })Mutation Rules
- Mutations must be synchronous
- Mutations are the only way to change state
- Mutations are tracked by devtools
- Mutations should be pure functions
See also: examples/core-concepts/mutations.md for detailed examples
Store API
API Reference
Vuex Store constructor options and instance methods.
Store Constructor Options
state
- Type:
Object | Function - Description: Root state object or function returning state
getters
- Type:
Object - Description: Getter definitions
mutations
- Type:
Object - Description: Mutation definitions
actions
- Type:
Object - Description: Action definitions
modules
- Type:
Object - Description: Module definitions
plugins
- Type:
Array<Function> - Description: Plugin functions
strict
- Type:
Boolean - Default:
false - Description: Enable strict mode
devtools
- Type:
Boolean - Default:
true - Description: Enable devtools
Store Instance Properties
store.state
- Type:
Object - Description: Root state
store.getters
- Type:
Object - Description: Root getters
Store Instance Methods
store.commit(type, payload, options)
- Commit mutation
- Parameters:
type- mutation type,payload- mutation payload,options- options
store.dispatch(type, payload, options)
- Dispatch action
- Parameters:
type- action type,payload- action payload,options- options
store.replaceState(state)
- Replace store state
- Parameters:
state- new state object
store.watch(getter, callback, options)
- Watch getter value
- Parameters:
getter- getter function,callback- callback function,options- options
store.subscribe(callback)
- Subscribe to mutations
- Parameters:
callback- callback function
store.subscribeAction(callback)
- Subscribe to actions
- Parameters:
callback- callback function
store.registerModule(path, module, options)
- Register dynamic module
- Parameters:
path- module path,module- module object,options- options
store.unregisterModule(path)
- Unregister dynamic module
- Parameters:
path- module path
See also: examples/core-concepts/ for detailed usage examples
Plugins
官方文档: https://vuex.vuejs.org/zh/,
Instructions
This example demonstrates plugins usage in Vuex.
Key Concepts
- Plugin definition
- Plugin registration
- Plugin usage
- Built-in plugins
Example: Basic Plugin
// plugins/logger.js
const logger = store => {
store.subscribe((mutation, state) => {
console.log(mutation.type, mutation.payload)
console.log('New state:', state)
})
}
export default loggerExample: Registering Plugin
// store/index.js
import logger from './plugins/logger'
const store = new Vuex.Store({
plugins: [logger],
state: {
count: 0
}
})Example: Plugin with Options
// plugins/logger.js
const logger = (store) => {
store.subscribe((mutation, state) => {
if (mutation.type.startsWith('user/')) {
console.log('User mutation:', mutation.type)
}
})
}
export default loggerExample: State Persistence Plugin
// plugins/persist.js
const persist = (store) => {
// Load state from localStorage
const savedState = localStorage.getItem('vuex-state')
if (savedState) {
store.replaceState(JSON.parse(savedState))
}
// Save state to localStorage on mutation
store.subscribe((mutation, state) => {
localStorage.setItem('vuex-state', JSON.stringify(state))
})
}
export default persistKey Points
- Plugins are functions
- Plugins receive store instance
- Use subscribe for mutations
- Use replaceState for state replacement
- Register plugins in store options
Actions
官方文档: https://vuex.vuejs.org/zh/,
Instructions
This example demonstrates actions usage in Vuex.
Key Concepts
- Action definition
- Action dispatch
- Action context
- Asynchronous operations
Example: Basic Action
// store/index.js
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
},
actions: {
increment(context) {
context.commit('increment')
}
}
})Example: Action with Payload
actions: {
incrementBy(context, payload) {
context.commit('increment', payload)
}
}Example: Async Action
actions: {
async fetchUser({ commit }, userId) {
const response = await fetch(`/api/users/${userId}`)
const user = await response.json()
commit('setUser', user)
}
}Example: Action Context Destructuring
actions: {
async fetchData({ commit, state, dispatch }) {
const response = await fetch('/api/data')
const data = await response.json()
commit('setData', data)
if (state.needsMore) {
dispatch('fetchMore')
}
}
}Example: Dispatching Actions
<template>
<div>
<button @click="increment">Increment</button>
<button @click="fetchUser(1)">Fetch User</button>
</div>
</template>
<script>
export default {
methods: {
increment() {
this.$store.dispatch('increment')
},
fetchUser(userId) {
this.$store.dispatch('fetchUser', userId)
}
}
}
</script>Example: Using mapActions
<template>
<div>
<button @click="increment">Increment</button>
<button @click="fetchUser(1)">Fetch User</button>
</div>
</template>
<script>
import { mapActions } from 'vuex'
export default {
methods: {
...mapActions(['increment', 'fetchUser'])
}
}
</script>Example: Action Returning Promise
actions: {
fetchData({ commit }) {
return new Promise((resolve, reject) => {
fetch('/api/data')
.then(response => response.json())
.then(data => {
commit('setData', data)
resolve(data)
})
.catch(error => {
reject(error)
})
})
}
}Key Points
- Actions can be asynchronous
- Dispatch actions via $store.dispatch
- Use mapActions helper
- Actions receive context object
- Actions commit mutations
Getters
官方文档: https://vuex.vuejs.org/zh/,
Instructions
This example demonstrates getters usage in Vuex.
Key Concepts
- Getter definition
- Getter access
- Getter arguments
- Computed properties
Example: Basic Getter
// store/index.js
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: 'Todo 1', done: true },
{ id: 2, text: 'Todo 2', done: false }
]
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
}
})Example: Getter with Arguments
getters: {
getTodoById: state => id => {
return state.todos.find(todo => todo.id === id)
}
}Example: Getter Accessing Other Getters
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
},
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
}
}Example: Accessing Getters in Components
<template>
<div>
<p>Done: {{ doneTodos.length }}</p>
</div>
</template>
<script>
export default {
computed: {
doneTodos() {
return this.$store.getters.doneTodos
}
}
}
</script>Example: Using mapGetters
<template>
<div>
<p>Done: {{ doneTodos.length }}</p>
<p>Count: {{ doneTodosCount }}</p>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters(['doneTodos', 'doneTodosCount'])
}
}
</script>Key Points
- Getters are computed properties
- Access via $store.getters
- Use mapGetters helper
- Getters are cached
- Can access other getters
Modules
官方文档: https://vuex.vuejs.org/zh/,
Instructions
This example demonstrates modules usage in Vuex.
Key Concepts
- Module definition
- Module namespacing
- Module state access
- Module mutations and actions
Example: Basic Module
// store/modules/user.js
const userModule = {
state: {
name: '',
email: ''
},
mutations: {
setName(state, name) {
state.name = name
}
},
actions: {
fetchUser({ commit }) {
// Fetch user data
commit('setName', 'John')
}
}
}
export default userModuleExample: Registering Module
// store/index.js
import userModule from './modules/user'
const store = new Vuex.Store({
modules: {
user: userModule
}
})Example: Namespaced Module
// store/modules/user.js
const userModule = {
namespaced: true,
state: {
name: ''
},
mutations: {
setName(state, name) {
state.name = name
}
},
actions: {
fetchUser({ commit }) {
commit('setName', 'John')
}
}
}Example: Accessing Namespaced Module
<template>
<div>
<p>{{ userName }}</p>
<button @click="fetchUser">Fetch User</button>
</div>
</template>
<script>
import { mapState, mapActions } from 'vuex'
export default {
computed: {
...mapState('user', ['name']),
userName() {
return this.$store.state.user.name
}
},
methods: {
...mapActions('user', ['fetchUser']),
fetchUser() {
this.$store.dispatch('user/fetchUser')
}
}
}
</script>Example: Accessing Root State
// In namespaced module
actions: {
someAction({ commit, state, rootState, rootGetters }) {
// Access root state
console.log(rootState.someRootState)
// Access root getters
console.log(rootGetters.someRootGetter)
// Commit root mutation
commit('someRootMutation', null, { root: true })
// Dispatch root action
dispatch('someRootAction', null, { root: true })
}
}Key Points
- Organize store with modules
- Use namespaced modules
- Access module state via namespace
- Access root state in modules
- Register modules in store
Mutations
官方文档: https://vuex.vuejs.org/zh/,
Instructions
This example demonstrates mutations usage in Vuex.
Key Concepts
- Mutation definition
- Mutation commit
- Mutation payload
- Synchronous mutations
Example: Basic Mutation
// store/index.js
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
},
decrement(state) {
state.count--
}
}
})Example: Mutation with Payload
mutations: {
increment(state, payload) {
state.count += payload.amount
},
setUser(state, user) {
state.user = user
}
}Example: Committing Mutations
<template>
<div>
<button @click="increment">Increment</button>
<button @click="incrementBy(10)">Increment by 10</button>
</div>
</template>
<script>
export default {
methods: {
increment() {
this.$store.commit('increment')
},
incrementBy(amount) {
this.$store.commit('increment', { amount })
}
}
}
</script>Example: Using mapMutations
<template>
<div>
<button @click="increment">Increment</button>
<button @click="decrement">Decrement</button>
</div>
</template>
<script>
import { mapMutations } from 'vuex'
export default {
methods: {
...mapMutations(['increment', 'decrement'])
}
}
</script>Example: Object-Style Commit
this.$store.commit({
type: 'increment',
amount: 10
})Key Points
- Mutations must be synchronous
- Commit mutations via $store.commit
- Use mapMutations helper
- Mutations receive state and payload
- Only way to change state
State
官方文档: https://vuex.vuejs.org/zh/,
Instructions
This example demonstrates state usage in Vuex.
Key Concepts
- State definition
- State access
- State reactivity
- Single source of truth
Example: State Definition
// store/index.js
const store = new Vuex.Store({
state: {
count: 0,
todos: [],
user: {
name: '',
email: ''
}
}
})Example: Accessing State in Components
<template>
<div>
<p>Count: {{ count }}</p>
<p>User: {{ user.name }}</p>
</div>
</template>
<script>
export default {
computed: {
count() {
return this.$store.state.count
},
user() {
return this.$store.state.user
}
}
}
</script>Example: Using mapState
<template>
<div>
<p>Count: {{ count }}</p>
<p>Todos: {{ todos.length }}</p>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
computed: {
...mapState(['count', 'todos'])
}
}
</script>Example: mapState with Object Syntax
<script>
import { mapState } from 'vuex'
export default {
computed: {
...mapState({
count: state => state.count,
todos: state => state.todos,
user: 'user'
})
}
}
</script>Example: State as Function
// For module reuse
const moduleA = {
state: () => ({
count: 0
})
}Key Points
- State is reactive
- Access via $store.state
- Use mapState helper
- State can be object or function
- Single source of truth
Installation
官方文档: https://vuex.vuejs.org/zh/,
Instructions
This example demonstrates how to install Vuex.
Key Concepts
- Package installation
- CDN installation
- Vue plugin registration
- Version compatibility
Example: Package Installation
# Using npm
npm install vuex@3
# Using yarn
yarn add vuex@3
# Using pnpm
pnpm add vuex@3Example: CDN Installation
<script src="https://unpkg.com/vuex@3"></script>Example: Vue Plugin Registration
// main.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)Example: Store Creation
// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
}
})
export default storeExample: Store Integration
// main.js
import Vue from 'vue'
import store from './store'
import App from './App.vue'
new Vue({
store,
render: h => h(App)
}).$mount('#app')Key Points
- Install vuex@3 for Vue 2
- Register Vuex as Vue plugin
- Create store instance
- Inject store into Vue instance
- Use store in components
Introduction
官方文档: https://vuex.vuejs.org/zh/,
Instructions
This example provides an introduction to Vuex.
Key Concepts
- What is Vuex
- Why use Vuex
- When to use Vuex
- Core concepts
Example: What is Vuex
Vuex is a state management pattern and library for Vue.js applications. It serves as a centralized store for all the components in an application.
Example: Why Use Vuex
- Centralized State: Single source of truth
- Predictable State Changes: State mutations are tracked
- DevTools Integration: Time-travel debugging
- Component Communication: Share state across components
Example: When to Use Vuex
Use Vuex when:
- Building large applications
- Multiple components share state
- Need to track state changes
- Complex state management required
Example: Core Concepts
- State: Application state (data)
- Getters: Computed properties for store
- Mutations: Synchronous state changes
- Actions: Asynchronous operations
- Modules: Store organization
Key Points
- Centralized state management
- Predictable state changes
- DevTools support
- Component communication
- Large application support
Quick Start
官方文档: https://vuex.vuejs.org/zh/,
Instructions
This example provides a quick start guide for Vuex.
Key Concepts
- Basic store setup
- State access
- Mutations
- Component usage
Example: Basic Store
// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
},
decrement(state) {
state.count--
}
}
})
export default storeExample: Component Usage
<template>
<div>
<p>{{ count }}</p>
<button @click="increment">+</button>
<button @click="decrement">-</button>
</div>
</template>
<script>
export default {
computed: {
count() {
return this.$store.state.count
}
},
methods: {
increment() {
this.$store.commit('increment')
},
decrement() {
this.$store.commit('decrement')
}
}
}
</script>Example: Using mapState
<template>
<div>
<p>{{ count }}</p>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
computed: {
...mapState(['count'])
}
}
</script>Example: Using mapMutations
<template>
<div>
<button @click="increment">+</button>
<button @click="decrement">-</button>
</div>
</template>
<script>
import { mapMutations } from 'vuex'
export default {
methods: {
...mapMutations(['increment', 'decrement'])
}
}
</script>Key Points
- Create store with state and mutations
- Access state via $store.state
- Commit mutations via $store.commit
- Use mapState and mapMutations helpers
- Inject store in Vue instance
What is Vuex
官方文档: https://vuex.vuejs.org/zh/,
Instructions
This example explains what Vuex is and its purpose.
Key Concepts
- State management pattern
- Centralized store
- Single source of truth
- Component communication
Example: State Management Problem
Without Vuex:
- Props drilling through multiple components
- Event bus for component communication
- Difficult to track state changes
- Hard to debug state issues
Example: Vuex Solution
With Vuex:
- Centralized state store
- Predictable state mutations
- DevTools integration
- Easy component communication
Example: Store Structure
const store = new Vuex.Store({
state: {
// Application state
},
getters: {
// Computed properties
},
mutations: {
// Synchronous state changes
},
actions: {
// Asynchronous operations
},
modules: {
// Store modules
}
})Example: Data Flow
Component → Dispatch Action → Commit Mutation → Update State → ComponentKey Points
- Centralized state management
- Single source of truth
- Predictable mutations
- DevTools support
- Better component communication
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Component Usage Templates
Accessing State
<template>
<div>{{ count }}</div>
</template>
<script>
export default {
computed: {
count() {
return this.$store.state.count
}
}
}
</script>Using mapState
<template>
<div>{{ count }}</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
computed: {
...mapState(['count'])
}
}
</script>Committing Mutations
<template>
<button @click="increment">Increment</button>
</template>
<script>
export default {
methods: {
increment() {
this.$store.commit('increment')
}
}
}
</script>Using mapMutations
<template>
<button @click="increment">Increment</button>
</template>
<script>
import { mapMutations } from 'vuex'
export default {
methods: {
...mapMutations(['increment'])
}
}
</script>Dispatching Actions
<template>
<button @click="fetchUser">Fetch User</button>
</template>
<script>
export default {
methods: {
fetchUser() {
this.$store.dispatch('fetchUser', 1)
}
}
}
</script>Using mapActions
<template>
<button @click="fetchUser(1)">Fetch User</button>
</template>
<script>
import { mapActions } from 'vuex'
export default {
methods: {
...mapActions(['fetchUser'])
}
}
</script>Store Setup Templates
Basic Store
// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
}
})
export default storeStore with All Features
// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import userModule from './modules/user'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
getters: {
doubleCount: state => state.count * 2
},
mutations: {
increment(state) {
state.count++
}
},
actions: {
incrementAsync({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
},
modules: {
user: userModule
}
})
export default storeModule Template
// store/modules/user.js
const userModule = {
namespaced: true,
state: {
name: '',
email: ''
},
getters: {
fullName: state => `${state.name} (${state.email})`
},
mutations: {
setName(state, name) {
state.name = name
}
},
actions: {
fetchUser({ commit }, userId) {
// Async operation
commit('setName', 'John')
}
}
}
export default userModule