英文:
Why is my dynamic Vue 3 page not reloading its content on page change?
问题
我有以下的Vue3模板文件,从Strapi获取数据。它在我的本地机器上工作,但是当我在线运行它时,内容只在第一次加载页面时加载,并且当我改变页面时不会改变(它已经设置为一个动态页面)。如果我刷新页面,就会加载正确的内容。URL也正确地改变了。
英文:
I have the following vue3 template file that fetches data from Strapi. It works on my local machine but when I run it online the content only loads on first page load and doesn't change when I change the page (It's all set up with one dynamic page). If I refresh the page the correct content is loaded. The URL also changes correctly.
<template>
<div v-if="!pending">
{{ route.params.slug }}
<div v-if="project.data[0]">
<Head>
<Title
>{{ project.data[0].attributes.title }} / Tuomoas Markunpoika</Title
>
</Head>
<div id="hero">
<img
:src="`${config.public.strapiURL}${project.data[0].attributes.preview.image.data.attributes.url}`"
/>
</div>
<ContentBlocks :blocks="project.data[0].attributes.content" />
<h2 v-if="project.data[0].attributes.items.data.length" class="main-heading">
Collection
</h2>
<ItemGrid v-if="project.data[0].attributes.items.data.length" :overview="`projects`" :selection="`${route.params.slug}`" />
</div>
</div>
</template>
<script setup>
const route = useRoute()
const config = useRuntimeConfig()
const { data: project, pending } = await useAsyncData("project", () =>
$fetch(
`${config.public.strapiURL}/api/projects/?filters[slug][$eq]=${route.params.slug}&populate[meta][populate]=*&populate[preview][populate]=*&populate[content][populate]=*&populate[items]=*`
)
)
if (!project.value || Object.keys(project.value.data).length === 0) {
throw createError({ statusCode: 404, statusMessage: "Page Not Found" })
}
</script>
答案1
得分: 1
你想使用一个观察者,在参数变化时重新请求数据。在你的情况下,可以像这样实现:
```javascript
const route = useRoute()
// 当参数变化时获取用户信息
watch(
() => route.params.slug,
async (newslug) => {
// 获取数据
},
);
更多信息:在设置函数内部访问路由和当前路由
<details>
<summary>英文:</summary>
You want to use a watcher that re-requests data when params change. So that can be something like this in your case:
```javascript
const route = useRoute()
// fetch the user information when params change
watch(
() => route.params.slug,
async (newslug) => {
// fetch data
},
);
More info: Accessing the Router and current Route inside setup
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论