Vue.js 中如何使用 Vuex 状态管理
在 Vue.js 的开发中,随着项目变得越来越复杂,组件之间的通信也变得越来越困难。在这种情况下,Vuex 状态管理就能够帮助我们更好地组织和管理我们的 Vue.js 项目。Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式,它可以让我们更好地管理组件的状态管理。
基本概念
在理解 Vuex 之前,需要先了解一下它的基本概念和架构。
- State(状态)
Vuex 的中心思想是将应用程序的数据存储在一个集中的地方——称为“store”。其中最重要的概念是“state”,它代表了应用程序的一个状态。
- Mutation(变化)
应用程序的状态只能通过“mutation”来修改。“mutation”是 Vuex 中更改状态的唯一方式。
- Action(动作)
“Action”提交“mutation”,而不是直接变异。“Action”可以包含任意异步操作。
- Getter(访问器)
“Getter”是“State”的派生状态,它可以通过Getter函数访问。
详细使用
1.安装
使用 Vuex 首先需要通过 npm 安装,执行以下命令进行安装:
npm install vuex --save
2.创建 Vuex store
在 Vue.js 应用程序中使用 Vuex 需要创建一个单一的 store 用于管理应用程序的状态。 创建一个新的 store 非常简单,只需要在您的应用程序的 entry file 中添加以下代码即可:
-- -------------------- ---- ------- ------ --- ---- ----- ------ ---- ---- ------ ------------- ----- ----- - --- ------------ ------ - ------ - -- ---------- - ---------------- - ------------- - -- -------- - ---------------- ------ -- - ------------- -- - ------------------- -- ----- - -- -------- - --------- ------- -- - ------ ----------- - - -- ------ ------- -----展开代码
3.注册 store
在主 Vue 实例中引入并注册上一步创建的 Vuex store。
import store from './store' new Vue({ el: '#app', store, render: h => h(App) })
4.使用状态
在组件中使用 Vuex 状态非常简单,只需要通过特定的访问器(例如 $store.state 或 $store.getters)来访问 Vuex Store 中维护的状态即可。
可以像下面这个例子通过 $store.state.count 访问状态:
<template> <div> <h1>Count: {{ $store.state.count }}</h1> <button @click="$store.commit('increment')">Increment</button> </div> </template>
也可以通过 $store.getters.getCount 的方式访问:
<template> <div> <h1>Count: {{ $store.getters.getCount }}</h1> <button @click="$store.dispatch('incrementAsync')">Increment</button> </div> </template>
5.修改状态
使用 Mutation
如上述所提到的,Mutation 是 Vuex 中更改状态的唯一方式。Mutation 看起来像这样:
mutations: { increment(state) { state.count++ } },
之后就可以在组件中通过提交 Mutation 来更改状态,如下所示:
<button @click="$store.commit('increment')">Increment</button>
使用 Action
当我们需要执行一个异步操作然后再通过 Mutation 来更改状态时,就需要用到 Action 了。
Action 通过 commit 调用 Mutation 来更改状态,例子如下:
actions: { incrementAsync({ commit }) { setTimeout(() => { commit('increment') }, 1000) } },
并且在组件中这样调用:
<button @click="$store.dispatch('incrementAsync')">Increment</button>
总结
在 Vue.js 应用程序中使用 Vuex 状态管理模式可以极大地帮助我们组织和管理组件的状态。我们可以创建单一的 store 用于存储应用程序的所有状态,然后通过访问器(例如 $store.state 或 $store.getters)来访问和修改其中维护的状态。另外,在进一步使用 Vuex 进行一些高级操作时,我们可以使用 Mutation 和 Action 在不同的场景下更改状态。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/64e01fcaf6b2d6eab3b3936e