将服务器的数据上传到vuex,并使用

在 mutations 中同步修改首页数据

const mutations={
	//修改首页数据
	changeIndexDatamutations(state,indexData){
		state.indexData=indexData;
	}
}

在 action 中异步请求数据

const actions={
	//发送网络请求,拿首页数据
	async getIndexDataActions({commit}){
		//1、执行异步任务,发送网络请求
		const res=await request('/getIndexData');//小程序
		//2、commit 触发 mutation
		commit('changeIndexDatamutations',res.indexData)
	}
}

在首页文件中引入模板函数

// vuex
import { mapActions, mapState } from 'vuex';	

在方法中使用模板函数

methods: {
        ...mapActions('home',['getIndexDataActions']), //映射home模块中的'getIndexDataAction'  映射完以后调用
}

在生命周期函数中调用,触发action

mounted() {
			//获取仓库里的测试数据
			console.log(this.$store.state.home.test);
			//1、触发action:this.$store.dispatch('模块名/action名')
			// this.$store.dispatch('home/getIndexDataActions')
			//2、触发action:映射以后直接调用
			this.getIndexDataActions();
			
			// this.getIndexData();
		},

数据上传完成

使用数据

将数据映射为计算属性后使用

computed:{//将仓库里的数据映射成计算属性
			//...mapState('模块',['数据'])
			// ...mapState('home',['indexData'])
			...mapState({
				indexData:state=>state.home.indexData
			})
		},

之后在组件中引入使用

	import { mapState } from "vuex"

 使用

import { mapState } from "vuex"
	export default {
		data() {
			return {

			};
		},
		computed:{
			...mapState({
				indexData:state=>state.home.indexData
			})
		}
	}
<!-- 2、 三个小图标    数据: policyDescList -->
		<view class="policyList">
			<view class="policyItem" v-for="item in indexData.policyDescList" :key="item.desc">
				<img :src="item.icon" alt="" />
				<text class="desc">{{item.desc}}</text>
			</view>
		</view>

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值