【问题标题】:Vue - Best way to poll the same API endpoint for multiple components simultaneouslyVue - 同时轮询多个组件的相同 API 端点的最佳方式
【发布时间】:2021-07-10 01:50:59
【问题描述】:

我需要为我的 NUXT 站点上的多个组件获取持续更新的 API 端点数据,其中 2 个在任何给定时刻同时可见。我想知道同时为几个可见的不同组件轮询同一端点的最佳做法是什么?

目前,我正在使用 VUEX 将 API 数据发送到我的组件,然后使用带有刷新功能的 setInterval 来更新每个组件中的数据。这显然是一个笨拙的解决方案(我是初学者)。我正在考虑直接在 VUEX 中轮询 API,但我知道这也不可取。

这是我目前(笨拙)的解决方案:

VUEX:

// STATE - Initial values
export const state = () => ({
  content: {}
});


// ACTIONS 
export const actions = {
    async nuxtServerInit ({ commit }) {
        const response = await this.$axios.$get('https://public.radio.net/stations/see15310/status');
        commit('setContent', response)
    }
}

// MUTATIONS 
export const mutations = {
    setContent(state, content) {
      state.content = content;
    }
  }

  

在每个组件中:

    computed: {
    content () {
      return this.$store.state.content
    },

    methods: {
      refresh() {
        this.$nuxt.refresh()
      }
    },

    mounted() {
      window.setInterval(() => {
        this.refresh();
      }, 5000);

【问题讨论】:

  • 适合您的用例的正确解决方案是在服务器上设置SSE。您的应用程序订阅它并提交每个收到的事件。任何渲染的组件都会对状态变化做出反应。这样,如果 2 天没有发生任何变化,您的应用程序中也不会发生任何变化。如果您每秒钟都收到一个事件,那么您不会错过任何一个事件。

标签: vue.js nuxt.js


【解决方案1】:

我认为,在 vuex 中进行轮询是一种正常的解决方案。 Vuex 是您的应用程序状态,也是所有依赖组件的一个真实来源。如果你需要为不同的组件更新一些类似的状态——在 vuex 操作中这样做是一个合理的解决方案。

另一个解决方案可能是事件总线。 First article about it from google

另外,我不建议使用 SetInterval 进行轮询。因为它不等待异步操作结束。如果客户端出现网络延迟或其他故障,这一事实可能会让您大吃一惊。为此,我使用了 SetTimeout

async function getActualData() {
  // get data from REST API
}

async function doPolling() {
  const newData = await getActualData() // waiting of finish of async function
  // update vuex state or send update event to event bus

  setTimeout(doPolling, 5000)
}

doPolling()

如果我的回答错过了您的问题,请给我更多详细信息。你想解决什么问题?你认为你的(用你的话;))“笨拙”的解决方案有什么缺点?

【讨论】:

  • 我尝试在我的代码中实现您的解决方案,但它没有返回任何状态:export const actions = { async nuxtServerInit() { const response = await this.$axios.$get('https://api.com'); return response }, async doPolling({ commit }) { const newData = await nuxtServerInit() commit('setContent', newData) setTimeout(doPolling, 5000) doPolling() }, }
  • 我也试过这个,但是空对象又回到了状态:export const actions = { async nuxtServerInit( {commit }) { const response = await this.$axios.$get('https://api.com/example'); setTimeout(() => commit('setContent', response), 3000); } }
  • 您在 nuxtServerInit 操作中编写了代码。此代码仅运行一次,并且仅从服务器端 Docs 运行。请检查文档并再试一次。如果您遇到问题,请告诉我。我尝试在我的 GitHub 中编写简单的项目
猜你喜欢
  • 1970-01-01
  • 2012-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-10
  • 1970-01-01
  • 2019-11-23
相关资源
最近更新 更多