vue.js Nuxt.js Hackernews API每分钟更新帖子而不加载页面

nbewdwxp  于 2022-12-14  发布在  Vue.js
关注(0)|答案(1)|浏览(112)

我有一个nuxt.js项目:https://github.com/AzizxonZufarov/newsnuxt2我需要从API更新职位每分钟没有加载页面:https://github.com/AzizxonZufarov/newsnuxt2/blob/main/pages/index.vue
我怎么能那样做呢?
请帮助结束代码,我已经写了一些代码,这个功能。我也有这个按钮的强制更新。它不工作了。它添加到以前的帖子。这不是我想要的,我需要强制更新帖子,当我点击它。
这是我目前掌握的情况

<template>
  <div>
    <button class="btn" @click="refresh">Force update</button>
    <div class="grid grid-cols-4 gap-5">
      <div v-for="s in stories" :key="s">
        <StoryCard :story="s" />
      </div>
    </div>
  </div>
</template>

<script>
definePageMeta({
  layout: 'stories',
})
export default {
  data() {
    return {
      err: '',
      stories: [],
    }
  },
  mounted() {
    this.reNew()
  },
  created() {
    /* setInterval(() => {
              alert()
        stories = []
        this.reNew()
        }, 60000) */
  },
  methods: {
    refresh() {
      stories = []
      this.reNew()
    },
    async reNew() {
      await $fetch(
        'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty'
      ).then((response) => {
        const results = response.slice(0, 10)
        results.forEach((id) => {
          $fetch(
            'https://hacker-news.firebaseio.com/v0/item/' +
              id +
              '.json?print=pretty'
          )
            .then((response) => {
              this.stories.push(response)
            })
            .catch((err) => {
              this.err = err
            })
        })
      })
    },
  },
}
</script>

<style scoped>
.router-link-exact-active {
  color: #12b488;
}
</style>
nqwrtyyt

nqwrtyyt1#

这就是如何高效地使用带有useLazyAsyncData钩子和setInterval 60s的Nuxt3来定期获取数据。
refreshData函数也是一个手动刷新数据的函数,如果您需要再次获取数据的话。
我们使用的是useIntervalFn,因此请不要忘记安装@vueuse/core

<template>
  <div>
    <button class="btn" @click="refreshData">Fetch the data manually</button>

    <p v-if="error">An error happened: {{ error }}</p>
    <div v-else-if="stories" class="grid grid-cols-4 gap-5">
      <div v-for="s in stories" :key="s.id">
        <p>{{ s.id }}: {{ s.title }}</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useIntervalFn } from '@vueuse/core' // VueUse helper, install it

const stories = ref(null)

const { pending, data: fetchedStories, error, refresh } = useLazyAsyncData('topstories', () => $fetch('https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty'))

useIntervalFn(() => {
  console.log('refreshing the data again')
  refresh() // will call the 'topstories' endpoint, just above
}, 60000) // every 60 000 milliseconds

const responseSubset = computed(() => {
  return fetchedStories.value?.slice(0, 10) // optional chaining important here
})

watch(responseSubset, async (newV) => {
  if (newV.length) { // not mandatory but in case responseSubset goes null again
    stories.value = await Promise.all(responseSubset.value.map(async (id) => await $fetch(`https://hacker-news.firebaseio.com/v0/item/${id}.json?print=pretty`)))
  }
})

function refreshData() { refreshNuxtData('topstories') }
</script>

相关问题