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

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

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.

  1. <template>
  2. <div v-if="!pending">
  3. {{ route.params.slug }}
  4. <div v-if="project.data[0]">
  5. <Head>
  6. <Title
  7. >{{ project.data[0].attributes.title }} / Tuomoas Markunpoika</Title
  8. >
  9. </Head>
  10. <div id="hero">
  11. <img
  12. :src="`${config.public.strapiURL}${project.data[0].attributes.preview.image.data.attributes.url}`"
  13. />
  14. </div>
  15. <ContentBlocks :blocks="project.data[0].attributes.content" />
  16. <h2 v-if="project.data[0].attributes.items.data.length" class="main-heading">
  17. Collection
  18. </h2>
  19. <ItemGrid v-if="project.data[0].attributes.items.data.length" :overview="`projects`" :selection="`${route.params.slug}`" />
  20. </div>
  21. </div>
  22. </template>
  23. <script setup>
  24. const route = useRoute()
  25. const config = useRuntimeConfig()
  26. const { data: project, pending } = await useAsyncData("project", () =>
  27. $fetch(
  28. `${config.public.strapiURL}/api/projects/?filters[slug][$eq]=${route.params.slug}&populate[meta][populate]=*&populate[preview][populate]=*&populate[content][populate]=*&populate[items]=*`
  29. )
  30. )
  31. if (!project.value || Object.keys(project.value.data).length === 0) {
  32. throw createError({ statusCode: 404, statusMessage: "Page Not Found" })
  33. }
  34. </script>

答案1

得分: 1

  1. 你想使用一个观察者在参数变化时重新请求数据在你的情况下可以像这样实现
  2. ```javascript
  3. const route = useRoute()
  4. // 当参数变化时获取用户信息
  5. watch(
  6. () => route.params.slug,
  7. async (newslug) => {
  8. // 获取数据
  9. },
  10. );

更多信息:在设置函数内部访问路由和当前路由

  1. <details>
  2. <summary>英文:</summary>
  3. You want to use a watcher that re-requests data when params change. So that can be something like this in your case:
  4. ```javascript
  5. const route = useRoute()
  6. // fetch the user information when params change
  7. watch(
  8. () =&gt; route.params.slug,
  9. async (newslug) =&gt; {
  10. // fetch data
  11. },
  12. );

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:

确定