首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在svelte中不刷新页面加载和动态路由

在svelte中不刷新页面加载和动态路由
EN

Stack Overflow用户
提问于 2021-06-26 19:20:31
回答 1查看 2.7K关注 0票数 2

使用graphql和动态路由不刷新页面的最佳方式是什么。我有一个名为kindergarten的文件,它在不刷新整个页面的情况下完美地加载:

代码语言:javascript
复制
<script context="module">
  import { gql, GraphQLClient } from 'graphql-request'

  export async function load() {
    const graphcms = new GraphQLClient(import.meta.env.VITE_GRAPHCMS_URL, {
      headers: {},
    })

    const query = gql`
      query MyQuery {
        terms(where: { taxonomies: CATEGORY }) {
          nodes {
            slug
            name
            termTaxonomyId
          }
        }
      }
    `

    const { terms } = await graphcms.request(query)

    return {
      props: {
        posts: terms.nodes,
      },
    }
  }
</script>

<script>
  import { SITE_NAME } from '$lib/store.js'
  let date = new Date()
  const [month, day, year] = [
    date.getMonth() + 1,
    date.getDate(),
    date.getFullYear(),
  ]
  export let posts = []
</script>

<svelte:head>
  <title>Sample Title - {SITE_NAME}</title>
  <meta
    name="description"
    content="Sample description  [Update: {year}/{month}/{day}]" />
</svelte:head>

{#each posts as post (post.termTaxonomyId)}
  <a
    tax-id={post.termTaxonomyId}
    href="/kindergarten/province/{post.slug}"
    target="blank">
    {post.name}
  </a>
  <br />
{/each}

此外,我还有另一页名为[slug].svelte

代码语言:javascript
复制
<script context="module">
  import { gql, GraphQLClient } from 'graphql-request'
  export async function load(ctx) {
    let slug = ctx.page.params.slug
    const graphcms = new GraphQLClient(import.meta.env.VITE_GRAPHCMS_URL, {
      headers: {},
    })

    const query = gql`
      query MyQuery {
        terms(where: { taxonomies: CATEGORY, slug: "${slug}" }) {
          nodes {
            name
            description
          }
        }
      }
    `

    const { terms } = await graphcms.request(query)
    return { props: { slug, post: terms.nodes } }
  }
</script>

<script>
  import { SITE_NAME } from '$lib/store.js'
  export let slug
  export let post
</script>

<svelte:head>
    <title>{post[0].name} - {SITE_NAME}</title>
</svelte:head>

<h1>Slug : {slug}</h1>
{#each post as data}
  <p>Name: {data.name}</p>
  <br />
  {#if data.description}
    <p>Description: {data.description}</p>
  {:else}
    <p>Ther is no Description</p>
  {/if}
{/each}

当我单击kindergarten页面上的链接时,它会转到子页面,但会刷新整个站点。

如何优化[slug].svelte 文件以防止刷新页面?

由于我是Svelte和Sveltekit的新手,所以任何优化整个代码的想法都是值得赞赏的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-06 18:43:29

您正在链接到一个新页面,所以它会刷新,因为它将转到一个全新的页面([slug].svelte)。听起来你想把数据加载到你的kindergarten.svelte页面上吗?在这种情况下,创建一个组件,而不是一个页面,在那里您可以将数据传递给组件,并且组件将被更新,而不是整个页面。查看这里的文档中的一个示例:https://svelte.dev/tutorial/component-bindings

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68145593

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档