Vuex 是专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
在 Vue 应用中,组件之间需要共享数据:
当应用变得复杂时,这种分散的状态管理方式变得难以维护。Vuex 提供了一个统一的状态管理中心,解决了这些问题。
单一状态树,存储应用的所有状态:
const store = new Vuex.Store({
state: {
count: 0,
user: null,
todos: []
}
})
类似计算属性,对 state 进行派生:
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: '学习 Vue', done: true },
{ id: 2, text: '学习 Vuex', done: false }
]
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
},
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
}
}
})
同步更改状态:
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
},
incrementBy(state, payload) {
state.count += payload.amount
}
}
})
异步操作,提交 mutation:
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
},
actions: {
incrementAsync({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
})
模块化组织代码:
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA
}
})
npm install vuex@3
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
},
actions: {
increment({ commit }) {
commit('increment')
}
},
getters: {
doubleCount: state => state.count * 2
}
})
new Vue({
store,
render: h => h(App)
}).$mount('#app')
export default {
computed: {
count() {
return this.$store.state.count
},
doubleCount() {
return this.$store.getters.doubleCount
}
},
methods: {
increment() {
this.$store.commit('increment')
},
incrementAsync() {
this.$store.dispatch('increment')
}
}
}
所有状态集中在一个地方,便于追踪和调试:
┌─────────────────────────────────────┐
│ Vuex Store │
│ ┌─────────────────────────────┐ │
│ │ State │ │
│ │ - user │ │
│ │ - products │ │
│ │ - cart │ │
│ └─────────────────────────────┘ │
│ ↑ │
│ ┌──────────────┼──────────────┐ │
│ │ │ │ │
│ ↓ ↓ ↓ │
│Component A Component B Component C│
└─────────────────────────────────────┘
通过 mutation 修改状态,每次变更都有记录:
store.commit('setUser', user)
配合 Vue Devtools,可以回退到任意状态:
mutation: setUser
mutation: addToCart
mutation: removeFromCart
← 回退到之前的状态
适合使用 Vuex 的场景:
不需要 Vuex 的场景:
学习 Vuex 的步骤: