1. Vuex 简介
Vuex是一个专为Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态。
// 创建store
const store = Vuex.createStore({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
}
})
// 在组件中使用
const app = Vue.createApp({
computed: {
count() {
return this.$store.state.count
}
},
methods: {
increment() {
this.$store.commit('increment')
}
}
})
2. State
State是Vuex存储的单一状态树,包含了应用的所有状态。
State示例
当前计数: {{ count }}
const store = Vuex.createStore({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
},
decrement(state) {
state.count--
}
}
})
3. Getters
Getters用于从state中派生出一些状态,类似于计算属性。
Getters示例
{{ todo.text }}
已完成: {{ completedCount }} / {{ totalCount }}
const store = Vuex.createStore({
state: {
todos: []
},
getters: {
completedCount: state => {
return state.todos.filter(todo => todo.completed).length
},
totalCount: state => {
return state.todos.length
}
}
})
4. Mutations
Mutations是更改Vuex的store中状态的唯一方法。
Mutations示例
{{ todo.text }}
const store = Vuex.createStore({
state: {
todos: []
},
mutations: {
addTodo(state, todo) {
state.todos.push(todo)
},
removeTodo(state, id) {
state.todos = state.todos.filter(todo => todo.id !== id)
}
}
})
5. Actions
Actions用于处理异步操作,可以包含任意异步操作。
Actions示例
加载中...
{{ item.name }}
const store = Vuex.createStore({
state: {
items: [],
loading: false
},
mutations: {
setItems(state, items) {
state.items = items
},
setLoading(state, status) {
state.loading = status
}
},
actions: {
async fetchData({ commit }) {
commit('setLoading', true)
try {
const response = await fetch('/api/items')
const items = await response.json()
commit('setItems', items)
} finally {
commit('setLoading', false)
}
}
}
})
6. Modules
Modules用于将store分割成模块,每个模块拥有自己的state、mutations、actions和getters。
const store = Vuex.createStore({
modules: {
cart: {
state: {
items: []
},
mutations: {
addToCart(state, item) {
state.items.push(item)
}
}
},
user: {
state: {
profile: null
},
mutations: {
setProfile(state, profile) {
state.profile = profile
}
}
}
}
})
7. 综合示例:购物车
下面是一个使用Vuex构建的购物车示例。
商品列表
{{ product.name }} - ¥{{ product.price }}
购物车
{{ item.name }} - ¥{{ item.price }}
总计: ¥{{ total }}
状态管理最佳实践
- 保持状态树扁平化
- 使用模块化管理大型应用
- 合理使用getters派生状态
- 通过actions处理异步操作
练习
尝试创建一个简单的任务管理系统,包含以下功能:
- 任务列表管理
- 任务分类管理
- 任务优先级设置
- 任务完成状态追踪
- 任务统计信息