You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Svelte中向动态路由传递多个参数实现详情页数据请求

问题解决方法

你无法获取id的核心原因是没有将id参数主动传递到路由系统中,SvelteKit的page.params仅会返回路由文件名中定义的动态参数,未显式传递的参数不会自动注入。下面提供3种常用解决方案:

方案1:路由参数携带ID(最推荐)

该方案将id作为路由的一部分,参数稳定不会因刷新丢失,也利于SEO。

  1. 修改路由文件结构:将原详情页路由src/routes/page/[slug].svelte改为src/routes/page/[slug]/[id].svelte(也可根据URL美观需求改为[slug]-[id].svelte)
  2. 修改列表页跳转链接:
{#each items.data as { id, item, href }}
    <li>
      <a href="/page/{href}/{id}">{ item }</a>
    </li>
{/each}
  1. 修改详情页load函数取值逻辑:
<script context="module">
  export const load = async ({ page, fetch }) => {
    const slug = page.params.slug;
    const id = page.params.id; // 可直接从路由参数获取
    const res = await fetch(`url/${id}`);
    const data = await res.json();
    return {
      props: {
        data,
      },
    };
  };
</script>

方案2:查询参数携带ID

该方案无需修改现有路由结构,适合快速调试或临时需求。

  1. 修改列表页跳转链接,将id作为查询参数拼接:
<a href="/page/{href}?id={id}">{ item }</a>
  1. 修改详情页load函数取值逻辑:
<script context="module">
  export const load = async ({ page, fetch }) => {
    const slug = page.params.slug;
    const id = page.url.searchParams.get('id'); // 从URL查询参数取值
    const res = await fetch(`url/${id}`);
    const data = await res.json();
    return {
      props: {
        data,
      },
    };
  };
</script>

方案3:全局状态存储ID

该方案适合不想让ID暴露在URL中的场景,注意页面刷新后状态会丢失,需要配合localStorage等持久化方案使用。

  1. 新建全局状态文件src/stores/itemStore.js:
import { writable } from 'svelte/store';
export const currentItemId = writable(null);
  1. 修改列表页为编程式跳转,跳转前存储ID:
<script>
  import { goto } from '$app/navigation';
  import { currentItemId } from '$stores/itemStore';
  export let items;
</script>

{#each items.data as { id, item, href }}
    <li>
      <a 
        href="/page/{href}" 
        on:click|preventDefault={() => {
          currentItemId.set(id);
          goto(`/page/${href}`);
        }}
      >{ item }</a>
    </li>
{/each}
  1. 详情页load函数从store中取值即可。

内容的提问来源于stack exchange,提问作者ak.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 08:27:03