0%

Vuex 状态管理

为什么需要状态管理?

在大型应用中,组件间共享状态变得复杂。Vuex 提供集中式状态管理,让状态变化可预测。

核心概念

State

存储应用状态。

1
2
3
4
5
const store = new Vuex.Store({
state: {
count: 0
}
})

Getters

计算属性,处理 state。

1
2
3
getters: {
doubleCount: state => state.count * 2
}

Mutations

同步修改 state。

1
2
3
4
5
mutations: {
increment (state) {
state.count++
}
}

Actions

异步操作,提交 mutations。

1
2
3
4
5
6
7
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}

在组件中使用

1
2
3
4
5
6
7
8
9
10
11
12
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'

export default {
computed: {
...mapState(['count']),
...mapGetters(['doubleCount'])
},
methods: {
...mapMutations(['increment']),
...mapActions(['incrementAsync'])
}
}

模块化

1
2
3
4
5
6
7
8
9
10
11
12
const moduleA = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... },
getters: { ... }
}

const store = new Vuex.Store({
modules: {
a: moduleA
}
})

严格模式

1
2
3
const store = new Vuex.Store({
strict: process.env.NODE_ENV !== 'production'
})

总结

Vuex 让状态管理清晰有序。开始时可能复杂,但对大型应用很有用。推荐配合 Vue DevTools 使用。