为什么我的动态Vue 3页面在页面更改时不重新加载内容?

huangapple go评论56阅读模式
英文:

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(
	() =&gt; route.params.slug,
	async (newslug) =&gt; {
		// fetch data
	},
);

More info: Accessing the Router and current Route inside setup

huangapple
  • 本文由 发表于 2023年5月13日 23:51:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76243643.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定