VueJS。分层调用未同步:网页 -> VUEX-> API 调用

Vue JS. Layered calls not synchronised: Web Page -> VUEX-> API call

我重构了我的 VUE JS 代码,使其具有专用的 API 层(调用 AWS Graphql 服务),它由 VUEX 层调用。它现在有以下级别:

     Web Page -> Vuex  -> API

我想在引用数据 (this.getActivities) 之前检索它(第 7 点)。为了简单起见,我已经减少了代码:

 async created() {
    console.log("Point 1")
    await this.getActivities();

  },
 mounted() {
    console.log("Point 7")
    // reference the data set by this.getActivities()
  },


  methods: {
    
    async getActivities() {
      // from DB
      console.log("Point 2")
     this.$store.dispatch('getAllActivities')  // vuex call

    },


VUEX DATA STORE

 actions: {

     async getAllActivities ({ commit }) {
      console.log("point 3")

      const activities = await queries.getActivities()
 
      console.log("point 6")
      commit('setActivities', activities)

    },


API
  async getActivities () {

    await API.graphql({
        query: listActivities
      }).then((response) => {

         console.log("Point 4")

      })
      
      console.log("Point 5")


    return activitiesList
  },

打印以下内容: 第 1 点 第 2 点 第3点 第 7 点 第8点 第 4 点 第 5 点 第 6 点

我想我误用了 await/sync 进程?

谢谢

假设您需要 1 个以上的活动列表 component/route(否则为什么要将此列表存储在 Vuex 而不是组件本身?!)您通常会这样做:

<template>
  <div>
    <ActivityItem v-for="act in ACTIVITY_LIST" :key="act.id" :activity="act" />
  </div>
</template>

<script>
import ActivityItem from './components/ActivityItem';
import { mapGetters, mapActions } from 'vuex';
import { ACTIVITY_LIST, FETCH_ACTIVITIES } from './store/constants';

export default
{
  components:
  {
    ActivityItem,
  },
  computed:
  {
    ...mapGetters([ACTIVITY_LIST]),
  },
  created()
  {
    this[FECH_ACTIVITIES]();
  },
  methods:
  {
    ...mapActions([FETCH_ACTIVITIES])
  }
}
</script>
// store/constants.js
export const ACTIVITY_LIST = 'ACTIVITY_LIST';
export const FETCH_ACTIVITIES = 'FETCH_ACTIVITIES';
export const SET_ACTIVITIES = 'SET_ACTIVITIES';
// store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
import { ACTIVITY_LIST, FETCH_ACTIVITIES, SET_ACTIVITIES } from './store/constants';
import myAPI from './api';

Vue.use(Vuex);

export default new Vuex.Store(
  {
    strict: process.env.NODE_ENV !== 'production',
    state()
    {
      return {
        activities: []
      };
    },
    getters:
    {
      [ACTIVITY_LIST](state)
      {
        return state.activities;
      }
    },
    mutations:
    {
      [SET_ACTIVITIES](state, value)
      {
        state.activities = value || [];
      }
    },
    actions:
    {
      [FETCH_ACTIVITIES]({ commit })
      {
        return myAPI.getActivities().then(response =>
        {
          commit(SET_ACTIVITIES, response.data.activitiesList);
          return response.data.activitiesList; // optional
        });
      }
    }
  });