一、Vuex是什么?
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状。Vuex 也集成到Vue 的官方调试工具
二、Vuex的安装与配置
1.安装+配置
- 安装npm install vuex -s
- 创建一个js文件并导入 improt Vuex from ‘vuex’
- 使用 Vue.use(Vuex)
- 创建实例 const store = new Vuex.store({})
- 导出实例 export default store
2.实例中配置的字段
export default new Vuex.Store({
state: {},//状态管理
mutations: {},//修改state中唯一的方法 (同步方法)
getters: {},//类似于计算属性 computed
actions: {},//异步方法
modules: {},//创建其他模块
});
三、Vuex的使用方法
state的使用方法
1. state(在组件中调用)
a. this.$store.state.属性
b. 通import {mapState} from 'vuex' 进行state映射, 将mapState映射到组件的computed(计算属性中)
mutations的使用方法
2. mutations(在组件中)
a. this.$store.commit(方法名,参数)
b.通过import {mapMutations} from 'vuex' 进行mutation映射, 将方法映射到methods中 通过this.方法名调用
actions的使用方法
3. actions(在组件中)
a. this.$store.dispatch(方法名,参数)
b.通过import {mapActions} from 'vuex' 进行Action映射, 将方法映射到methods中 通过this.方法调用
getters的使用方法
4. getters(在组件中)
a. this.$store.getters.属性名
b. 通过import {mapGetters} from 'vuex' 进行getters映射, 将属性映射到组件的computed(计算属性中)
四.Vuex的使用规范(包括怎么在外部调用)
-
- Vuex是Vue提供的一种跟数据共享仓库,在开发中大型的项目中可以使用到.主要就是提供了一种对公共数据存储的一种方式,避免我们频繁的进行多个组件之间的传值
-
- mutation(state,参数)中的方法修改state中的数据,(除了mutation以外的方式,都不推荐使用) 同步方法
-
- actions(context) 中的方法是用来处理异步操作,修改state中的数据需要使用$commit去调用mutation中修改state的方法
-
- getters(state) 中的方法可以理解成是计算属性,具有缓存,只读属性
-
- module 如果单个仓库不能满足我们的使用, 我们可在module中定义其他的仓库,同时声明name:仓库名(模块名)