背景
登录系统之后,需要初始化一些全局数据,然后存到store里,在需要使用的时候直接从store里面获取即可
初始化数据的时机
登录成功进入系统,在layout组件中调用接口获取数据(layout组件是系统界面的基本布局,组件层级是: App -> Layout -> Pages,登录系统之后,所有的页面组件都是在其下的)
在layout组件的 beforeCreate生命周期中调用接口,具体代码如下
<template><div class="Main"><router-view></router-view></div></template><script>import { mapActions } from "vuex";export default {name: 'Main',props: {},components: {},data() {return {}},computed: {},watch: {},// INIT STOREasync beforeCreate() {// 获取所有产品分类await this.$store.dispatch('product/getAllCatagory');// ⚠ mapActions执行在beforeCreated之后,// 在beforeCreated里不能直接调用通过mapActions映射的函数,必须写dispatch// await this.initStore()},created() { },mounted() { },methods: {...mapActions('product', ['getAllCatagory']),async initStore() {await this.getAllCatagory()}},updated() { },beforeDestroy() { }}</script><style lang='less' rel='stylesheet/less' scoped>.Main {position: absolute;width: 100%;height: 100%;overflow-y: auto;}</style>
注意
mapActions执行在beforeCreated之后- 在
beforeCreated里不能直接调用通过mapActions映射的函数,必须写dispatch - 子组件里的接口调用并不会因为
layout组件里写了async await就在其后执行,倘若子组件需要用到store里面的数据,可以在子组件里面增加computed处理
