【问题标题】:Passing mulitple parameters to dynamic route in Svelte将多个参数传递给 Svelte 中的动态路由
【发布时间】:2021-12-08 17:12:09
【问题描述】:

我正在尝试使用 Svelte 的第一个项目,但我遇到了这样的情况:

我从如下 API 获取结果列表:

# Page with a list of items

<script context="module">
  export const load = async ({ page, fetch }) => {
    const res = await fetch(`url`);
    const items = await res.json();
    return {
      props: {
        items,
      },
    };
  };
</script>

<script>
  export let items;
</script>

{#each items.data as { id, item, href }}
    <li>
      <a href="/page/{href}">{ item }</a>
    </li>
{/each}

我正在尝试将多个参数传递给下一个(动态)路由,以便 href 是 slug 和 id 是 id 用于从 API 获取项目详细信息,如下所示:

# Page with a single item

<script context="module">
  export const load = async ({ page, fetch }) => {
    const slug = page.params.slug; <-- I can get this
    const res = await fetch(`url/${page.id}`); <-- but not this
    const data = await res.json();
    return {
      props: {
        data,
      },
    };
  };
</script>

我为我的无知道歉,但我真的很挣扎,我不知道如何准确地解决这个问题。我会很感激任何提示。

【问题讨论】:

    标签: javascript svelte dynamic-routing


    【解决方案1】:

    有两种选择

    一个是有第二个'slug',这意味着你有一个像/page/[slug]/[id].svelte这样的文件结构,在这种情况下你可以简单地做const { slug, id } = page.params;并且你的锚变成&lt;a href="/page/{href}/{id}"&gt;。这样做的缺点是,如果人们浏览到 /page/{href} 而不传递 id,您仍然必须找到一种处理方法。

    另一种选择是将 id 作为查询参数传递,这里你的锚点是&lt;a href="/page/{href}?id={id}"&gt; 文件就像你所拥有的一样,你得到的查询参数如下const id = page.query.get('id')。如果人们在没有 id 的情况下访问此页面,您仍然需要处理,但在这种情况下,id 将是未定义的,因此处理起来可能会更容易一些。

    【讨论】:

      猜你喜欢
      • 2022-10-18
      • 2018-08-19
      • 2019-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-10
      • 1970-01-01
      相关资源
      最近更新 更多