我正在尝试使用 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
is the slug
and id
is the 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>
我为我的无知道歉,但我真的很挣扎,我不知道如何准确解决这个问题。我将不胜感激任何提示。
有两种选择:
一种是有第二个“slug”,这意味着您有一个像这样的文件结构/page/[slug]/[id].svelte
,在这种情况下你可以简单地做const { slug, id } = page.params;
你的锚就变成了<a href="/page/{href}/{id}">
。这样做的缺点是,如果人们浏览到,您仍然需要找到一种方法来处理/page/{href}
无需传递 id。
另一种选择是将 id 作为查询参数传递,这里你的锚点是<a href="/page/{href}?id={id}">
这些文件就像您所拥有的那样,您将获得如下查询参数const id = page.query.get('id')
。如果人们没有 id 就来到这个页面,你仍然需要处理,但在这种情况下id
将是未定义的,所以它可能更容易处理。
2023 年 2 月 3 日更新
自这个答案以来,SvelteKit 发生了一些变化。最重要的是加载函数不再位于带有“context =“module””的脚本中,而是位于它自己的文件中。
这两个选项的加载函数本身看起来仍然非常相似:
export const load = (async ({ params, url }) => {
// option 1
const { key, title } = params;
// option 2
const title = params.title;
const id = url.searchParams.get('id');
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)