Vuex
- 是vue项目中实现大范围数据共享的技术方案
- 能够方便、高效地实现组件内数据共享
- 存储的数据都是响应式的
- 使用步骤:
- 下载依赖包。yarn add vuex
- 导入 Vuex 模块
- Vue.use(Vuex)
- 创建 store 实例对象。const store = new Vuex.Store({ })
- 挂载到 Vue 身上。new Vue ({ store })
1.state对象
- 存储全局共享的数据
- 在 main.js 中定义 state 数据。const store = new Vuex.Store({ state:{数据:值} })
- 访问数据:
- 在组件中插入表达式。{{ this.$store.state.数据 }}
- 在组件中导入 mapState 函数,import { mapState } from ‘vuex’。映射为计算属性。computed:{ …mapState([‘数据’]) }。在组件中插入表达式,{{ 数据 }}
2.Mutation对象
- 本质上是js函数,专门用来修改 State 中的数据。
- 所有数据修改都必须使用 Mutation
- 在 main.js 中定义 mutations 对象。const store = new Vuex.Store({ mutations:{函数名(){} } })
- 在组件中调用方法:
- 在组件中使用方法,@click = $store.commit(‘函数名’)
- 在组件中导入 mapMutations 函数,import { mapMutations } from ‘vuex’。映射为方法。methods:{ …mapMutations([‘函数名’]) }。在组件中使用方法,@click = ‘函数名’
- 载荷。mutations 只能有两个参数,第一个必须是 state ,第二个是 payload。如果有多个参数,就在第二个参数传入对象,定义多个属性。
3.Action对象
- 本质是js函数,专门用来处理 Vuex 中的异步操作
- 在 main.js 中定义 actions 对象。const store = new Vuex.Store({ actions:{异步函数名(){} } })
- 在组件中调用方法:
- 在组件中使用方法,@click = $store.dispatch(‘函数名’)
- 在组件中导入 mapActions 函数,import { mapActions } from ‘vuex’。映射为方法。methods:{ …mapActions([‘函数名’]) }。在组件中使用方法,@click = ‘函数名’
- 载荷。actions 的第一个参数必须是 context ,就是为了让 actions 内可以调用 mutation 对象
4.Getter对象
- 本质是js函数,是 Vuex中的计算属性。State 数据源发生变化,getter 返回值自动更新
- 在 main.js 中定义 getters 对象。const store = new Vuex.Store({ getters:{函数名(){} } })
- 在组件中调用方法:
- 在组件中使用方法,{{ $store.getters.函数名 }}
- 在组件中导入 mapGetters 函数,import { mapGetters } from ‘vuex’。映射为方法。methods:{ …mapGetters([‘函数名’]) }。在组件中使用方法,{{ 函数名 }}
- 载荷。getters 的第一个参数必须是 state
5.Module对象
- 定义模块。分离模块,使用模块化开发思想对 Vuex 进行拆分,方便后期维护管理。
- 定义模块:利用 namespaced:true 开启命名空间。四大成员一样,state 变成函数。state:() => ({ })
- 注册模块。modules:{ 注册模块名:模块对象 }
- 使用子模块。访问数据。…mapState(‘模块名’,[‘要映射的数据或函数’])