vue中在vuex的actions中请求数据

本文介绍了一个使用Vuex进行状态管理的例子,展示了如何通过actions、getters和mutations模块来实现认证状态的获取与更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

actions.js
    getCertificationStatus(context, {vm:vm,type:type}){
    	return new Promise((resolve, reject) => {
	      axios.post('/realNameUtils/gotoStatusPage')
	      .then((res)=>{
	        	context.commit('certificationStatus',res.data.content)
	        	if(type=='1'){//个人
                    
	        	}else if(type=='2'){//企业

	        	}else if(type=='0'){//个人+企业

	        	}
	        	resolve()
			})
		})
  	}
getters.js
    certificationStatus :(state)=>{
		return state.certificationStatus
	}
mutations.js
    var state = {
	    certificationStatus: null
    }
const mutations= {
    certificationStatus(state,data){
		state.certificationStatus = data
	}
}
组件:
    import {mapGetters} from 'vuex'
    computed: {
	        ...mapGetters([
		        "certificationStatus"
		      ])
	    }
    this.$store.dispatch('getCertificationStatus',{vm:this,type:'1'})

就是这样就可以了  有疑问可以一起讨论哦

Vue2.7中,可以使用Vuex来进行接口请求数据的存储。首先需要安装vuex: ``` npm install vuex --save ``` 然后在store文件夹下创建一个store.js文件,引入Vuex并创建一个store对象: ``` import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state: { data: null }, mutations: { setData(state, payload) { state.data = payload } }, actions: { fetchData(context) { // 发起接口请求 axios.get('/api/data') .then(res => { context.commit('setData', res.data) }) .catch(err => { console.log(err) }) } } }) export default store ``` 在state中定义一个data属性用来存储接口返回的数据,在mutations中定义一个setData方法用来更新state中的data属性,在actions中定义一个fetchData方法用来发起接口请求,并在请求成功后调用mutations中的setData方法来更新state中的data属性。 在Vue组件中可以通过以下方式来访问store中的data数据: ``` <template> <div> <div v-if="data">{{ data }}</div> <div v-else>暂无数据</div> <button @click="fetchData">获取数据</button> </div> </template> <script> import { mapState, mapActions } from 'vuex' export default { computed: { ...mapState(['data']) }, methods: { ...mapActions(['fetchData']) }, mounted() { this.fetchData() } } </script> ``` 在computed中通过mapState来获取store中的data数据,在methods中通过mapActions来调用store中的fetchData方法来发起接口请求。在组件的mounted钩子函数中调用fetchData方法来在组件渲染时就获取数据
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值