【问题标题】:How to display objects from VueX using fetched data from an API如何使用从 API 获取的数据显示来自 VueX 的对象
【发布时间】:2020-06-18 02:39:46
【问题描述】:

我正在尝试使用VueX 和来自 rapidapi 的免费 API 来显示数据。不知何故,我无法在组件中正确显示或遍历它。

控制台正确显示对象,但应该显示它的组件却没有。

我做错了什么?

以下是相关代码:

store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
export default new Vuex.Store({
  state: {
    worldData:     
      fetch("https://covid-193.p.rapidapi.com/statistics", {
        method: "GET",
        headers: {
          "x-rapidapi-host": "covid-193.p.rapidapi.com",
          "x-rapidapi-key": "mySecretKey"
        }
      })
    .then(response => response.json())
    .then(data => {
      data.response.sort((a, b) => (a.country > b.country ? 1 : -1));
      console.log(data.response);
      return data.response;
    })
  },
  getters: {
    worldData: state => state.worldData,
  },
  mutations: {
  },
  actions: {
  },
  modules: {
  }
})

components/mycomponent.vue

<template>
      <div >  
        <div v-for="myData in $store.getters.worldData" :key="myData">{{myData}}</div>
      </div>
</template>

【问题讨论】:

  • country 是什么数据类型?是字符串还是数字?
  • 这是一个字符串。如上所述,控制台实际上在检查器中正确显示了对象。 :)

标签: api vue.js vuex


【解决方案1】:

创建商店时,state 属性用于初始/默认值。您目前正在将您的设置为 Promise,这可能不是您想要的。

应通过actions 执行异步任务,并通过mutations 提交结果。

const store = new Vuex.Store({
  state: {
    worldData: [] // initial value
  },
  getters: {
    worldData: state => state.worldData
  },
  mutations: {
    setWorldData: (state, worldData) => state.worldData = worldData
  },
  actions: {
    loadWorldData: async ({ commit }) => {
      // load the data via fetch
      const res = await fetch('https://covid-193.p.rapidapi.com/statistics', {
        headers: {
          "x-rapidapi-host": "covid-193.p.rapidapi.com",
          "x-rapidapi-key": "mySecretKey"
        }
      })

      // check for a successful response
      if (!res.ok) {
        throw res
      }

      // parse the JSON response
      const worldData = (await res.json()).response

      // commit the new value via the "setWorldData" mutation
      commit('setWorldData', worldData.sort((a, b) => a.country.localeCompare(b.country)))
    }
  }
})

store.dispatch('loadWorldData') // dispatch the action to load async data
export default store

您可以随时随地执行dispatch来加载/重新加载数据。

【讨论】:

  • 谢谢。但是我在使用该解决方案时遇到了编译错误。关于意外令牌,预期的“(”并指向 loadWorldData^:。抱歉,我不知道这个的正确语法。
  • @Artvader 我之前写了一些错别字。请再次检查并确保您看到我的回答的最新更新
  • 现在编译正确。虽然有一个控制台错误说 Uncaught (in promise) TypeError: worldData.sort is not a function。我试图弄清楚。谢谢。
  • 啊抱歉,我错过了该属性被称为response。我现在已经确定了答案
猜你喜欢
  • 2021-12-03
  • 2018-07-05
  • 2021-11-08
  • 2022-12-18
  • 1970-01-01
  • 1970-01-01
  • 2017-06-09
  • 2020-02-09
  • 1970-01-01
相关资源
最近更新 更多