Vue JS.分层调用未同步:网页->VUEX->API调用

2022-08-04 00:00:00 vue.js vuex

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

     Web Page -> Vuex  -> API

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

 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点 第三点 第7点 第8点 第4点 第5点 第6点

我想我误用了等待/同步进程?

谢谢


解决方案

假设您需要多个组件/工艺路线中的活动列表(否则为什么要将此列表存储在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
        });
      }
    }
  });

相关文章