
使用场景:共享
1。多个组件依赖于同一个状态(数据)。
2.来自不同组件的行为需要变更同一状态。

在 Actions 中发送ajax请求。
Vuex中有三个东西:Actions、Mutations、State,这些都被store管理着。


允许直接commit到Motations。
1.创建src/store/index.js文件:
作用:初始化数据、配置actions、配置mutations
- // 该文件用于创建Vuex中最为核心的store
-
- // 引入Vuex
- import Vuex from 'vuex'
- import Vue from 'vue'
-
- // 准备actions---用于响应组件中的动作
- const actions ={
- // jia:function(){
- // console.log("actions中的jia被调用了");
- // }
- jia(context,value){
- console.log("actions中的jia被调用了");
- context.commit("JIA",value)
- },
- jian(context,value){
- console.log("actions中的jian被调用了");
- context.commit("JIAN",value)
- },
- // 当sum为奇数的时候在 加
- jiaOdd(context,value){
- console.log("actions中的jiaOdd被调用了");
- if(context.state.sum % 2){
- context.commit("JIA",value)
- }
- },
- // 等一等再加
- jiaWait(context,value){
- console.log("actions中的jiaWait被调用了");
- setTimeout(()=>{
- context.commit("JIA",value)
- },500)
- },
- }
-
- // 准备mutations--用于操作数据(state)
- const mutations = {
- JIA(state,value){
- console.log("mutations中的JIA被调用了");
- state.sum += value;
- },
- JIAN(state,value){
- console.log("mutations中的JIAN被调用了");
- state.sum -= value;
- }
- }
-
- // 准备state---用于存储数据
- const state = {
- sum:0 //用于求和:当前的和
- }
-
- // 准备getters--用于将state中的数据进行加工
- const getters ={
- bigSum(state){
- return state.sum *10;
- }
- }
-
- Vue.use(Vuex)
- // 创建store
- const store = new Vuex.store({
- actions:actions,
- mutations:mutations,
- state:state,
- getters,
-
- })
-
- // 暴露store
- export default store
2. 在main.js中,创建vm时传入store配置项:

3. 在组件中读取Vuex中的数据:

4.组件中修改Vuex中的数据:

5.getters的使用:
使用场景:当state中的数据需要经过加工后再使用时,再getters中进行加工。
1)再src/store/index.js中:

2)在组件中读取getters中的数据:

二。mapState方法和mapGetters方法
1)mapState方法:用于帮助我们映射state中的数据为计算属性。

2)mapGetters方法:用于帮助我们映射getters中的数据为计算属性。
