Vuex 是一个专门为 Vue.js 应用程序开发的状态管理模式,它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。Vuex 将应用的状态(数据)抽离出来,以一个全局单例模式管理,这样就可以方便地实现在不同的组件中共享数据。
Vuex 包含了以下核心概念:
- State:驱动应用的数据源
- Getter:从 Store 中获取数据
- Mutation:更改 Store 中的数据
- Action:异步操作和提交多个 Mutation
下面是一个简单的 Vuex 使用示例:
// 定义一个 store 对象
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++;
}
},
actions: {
incrementAsync({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
})
// 在组件中使用
<template>
<div>
<p>{{ count }}</p>
<button @click="increment">+</button>
<button @click="incrementAsync">+ Async</button>
</div>
</template>
<script>
export default {
computed: {
count() {
return this.$store.state.count;
}
},
methods: {
increment() {
this.$store.commit('increment');
},
incrementAsync() {
this.$store.dispatch('incrementAsync');
}
}
}
</script>
在这个示例中,我们定义了一个名为 store
的 Vuex Store 对象。该对象包含一个状态属性 count
,以及两个函数:一个用于同步地增加计数器值的 Mutation 函数 increment
,和一个用于异步地增加计数器值的 Action 函数 incrementAsync
。
然后,在组件中,我们使用 $store.state.count
来获取状态数据,并使用 $store.commit('increment')
和 $store.dispatch('incrementAsync')
来分别提交 Mutation 和 Action 以更改数据。