我有一个 nuxt.js 项目:https://github.com/AzizxonZufarov/newsnuxt2 https://github.com/AzizxonZufarov/newsnuxt2我需要每分钟更新 API 的帖子而不加载页面:https://github.com/AzizxonZufarov/newsnuxt2/blob/main/pages/index.vue 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>
这就是您如何有效地使用 Nuxt3useLazyAsyncData
钩子和一个setInterval
60s 定期获取数据。在使用之上async/await
而不是.then
.
The refreshData
如果您需要再次获取数据,该功能也是手动刷新数据。
我们正在使用useIntervalFn https://vueuse.org/shared/useintervalfn/#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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)