Vuex 是 Vue.js 应用程序的状态管理模式,它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。以下是使用 Vuex 的基本步骤以及一个简单的计数器实例来说明其工作原理:
步骤1:安装和引入 Vuex
首先,在你的 Vue 项目中通过 npm 或 yarn 安装 Vuex:
npm install vuex --save
或者
yarn add vuex
然后在项目的主入口文件(如 src/main.js)中引入 Vuex 并将其注册到 Vue 实例中:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
// state, mutations, actions, getters 将在这里定义
})
步骤2:定义 State
State 是 Vuex 中用于存储应用状态的数据对象。
const store = new Vuex.Store({
state: {
count: 0 // 我们的全局状态,初始值为 0
},
// ...
})
步骤3:定义 Mutations
Mutations 是唯一更改 Vuex 状态的地方,它们是同步的,且每个 mutation 都有一个字符串类型的事件类型和一个回调函数。
const store = new Vuex.Store({
state: { count: 0 },
mutations: {
increment (state) {
state.count++
},
decrement (state) {
state.count--
}
},
// ...
})
步骤4:提交 Mutations
组件中通过 this.$store.commit('mutationType', payload)
来触发 mutation 更新状态:
methods: {
increment() {
this.$store.commit('increment')
},
decrement() {
this.$store.commit('decrement')
}
}
步骤5:定义 Actions
Actions 可以包含异步操作,并通过 dispatch 方法调用,最终会提交 mutations 更新状态。
const store = new Vuex.Store({
// ...
actions: {
async incrementAsync({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
})
在组件中 dispatch action:
methods: {
async incrementAfterDelay() {
await this.$store.dispatch('incrementAsync')
}
}
步骤6:定义 Getters
Getters 是从 store 中派生出的状态,可用于计算或过滤 state 数据,类似于 Vue 的 computed 属性。
const store = new Vuex.Store({
// ...
getters: {
evenCount: state => state.count % 2 === 0
}
})
在组件中使用 getter:
computed: {
evenOrOdd() {
return this.$store.getters.evenCount ? 'Even' : 'Odd'
}
}
组件内使用 Store
最后,在 Vue 组件中注入 store,并开始使用这些状态和方法:
<template>
<div>
Count: {{ $store.state.count }}
<button @click="increment">Increment</button>
<button @click="decrement">Decrement</button>
<p>Is Even: {{ evenOrOdd }}</p>
</div>
</template>
<script>
export default {
methods: {
increment() {
this.$store.commit('increment')
},
decrement() {
this.$store.commit('decrement')
}
},
computed: {
evenOrOdd() {
return this.$store.getters.evenCount
}
}
}
</script>
以上就是一个非常基础的 Vuex 使用示例。在实际开发中,你可能会有更复杂的状态管理和模块化的需求,但核心概念是一致的。