背景

登录系统之后,需要初始化一些全局数据,然后存到store里,在需要使用的时候直接从store里面获取即可

初始化数据的时机

登录成功进入系统,在layout组件中调用接口获取数据(layout组件是系统界面的基本布局,组件层级是: App -> Layout -> Pages,登录系统之后,所有的页面组件都是在其下的)

layout组件的 beforeCreate生命周期中调用接口,具体代码如下

  1. <template>
  2. <div class="Main">
  3. <router-view></router-view>
  4. </div>
  5. </template>
  6. <script>
  7. import { mapActions } from "vuex";
  8. export default {
  9. name: 'Main',
  10. props: {},
  11. components: {},
  12. data() {
  13. return {}
  14. },
  15. computed: {},
  16. watch: {},
  17. // INIT STORE
  18. async beforeCreate() {
  19. // 获取所有产品分类
  20. await this.$store.dispatch('product/getAllCatagory');
  21. // ⚠ mapActions执行在beforeCreated之后,
  22. // 在beforeCreated里不能直接调用通过mapActions映射的函数,必须写dispatch
  23. // await this.initStore()
  24. },
  25. created() { },
  26. mounted() { },
  27. methods: {
  28. ...mapActions('product', ['getAllCatagory']),
  29. async initStore() {
  30. await this.getAllCatagory()
  31. }
  32. },
  33. updated() { },
  34. beforeDestroy() { }
  35. }
  36. </script>
  37. <style lang='less' rel='stylesheet/less' scoped>
  38. .Main {
  39. position: absolute;
  40. width: 100%;
  41. height: 100%;
  42. overflow-y: auto;
  43. }
  44. </style>

注意

  • mapActions执行在beforeCreated之后
  • beforeCreated里不能直接调用通过mapActions映射的函数,必须写dispatch
  • 子组件里的接口调用并不会因为layout组件里写了 async await就在其后执行,倘若子组件需要用到store里面的数据,可以在子组件里面增加computed处理