vuex actios

    export default new Vuex.Store({
      //存储数据
      state:{

      },
      //方法
      mutations:{

      },
      //计算属性
      getters:{

      },
      //异步方法,(如ajax)
      actions:{

          (1)创建mutations内的方法
          		其中:
          		1、这里设置的方法,第一个参数是context上下文对象,即store实例,第二个参数是传入的参数
          		2、修改state中的数据,需要使用mutations内的方法,第一个形参.commit('方法名')调用,形参也可以使用es6解构赋值,{commit,state,getters,dispatch}
          		3、function(context/{commit,state,getters,dispatch},参数){...}
			
		  (2)调用一:通过this.$store.dispatch('函数名',参数)调用
		  
          (4)调用二:使用mapActions辅助,在methods方法里解构
              methods:mapActions{['方法名']}
              methods:mapActions{键名:'方法名'}
      ,		  methods:{
      					...mapActions(['xx','xx',...])
      					}
      //模块
      modules:{

      }
    })

代码示例:
store

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

//仓库对象,存放多组件共用数据
export default new Vuex.Store({
  //data
  state:{
      num:0,
      age:17,
      sex:'male'
  },
  //methods,尽量在这里处理state中的状态
  mutations:{
      changeNum:function(state,val)
      {
        state.num=val;
      }
  },
  //计算属性
  getters:{

  },
  //异步方法(如ajax)
  actions:{
    getMsgss:function(context){
      fetch('http://api.tianapi.com/txapi/ncov/index?key=4a8edfc8ac5eae9b0c5bf08157abba96')
      .then(data=>data.json())
      .then(res=>{console.log(res)
        context.commit('changeNum',123);
        })
      }
  },
  //模块
  modules:{

  }
})

组件:

<template>
  <div>

  <button @click='getMsgss'>点击获取{{num}}</button>
  </div>
</template>

<script>
  import {mapState,mapActions} from 'vuex'

  export default{
    name:'A',
    data()
    {
      return{
         count:0
      }
    },
    methods:{
        get:function()
        {
          this.$store.dispatch('getMsg');
        }
    },
    computed:{
      // ...mapState(['num']),
      ...mapActions(['getMsgss'])
    }
  }
</script>

<style>
</style>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值