在 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>