[英]Routing in Svelte: how to get information from a list?
I want to create a simple webshop.我想创建一个简单的网上商店。 On the page "products" a list of all offered products will be listed.
在“产品”页面上,将列出所有提供的产品的列表。 When clicking into one product I want to show the ID and the name of the product.
单击一个产品时,我想显示产品的 ID 和名称。 However, I am only able to display the ID of the product since I am getting it from the URl. Is there a method to also get the name out of the list by having the id?
但是,我只能显示产品的 ID,因为我是从 URl 获取它的。有没有一种方法可以通过 ID 从列表中获取名称?
Products:产品:
<script>
let products = [
{
id: 0,
name: "Superbike",
},
{
id: 1,
name: "Ultrabike",
},
];
</script>
<h1>Products</h1>
<ul>
{#each products as product}
<li><a href={"#/products/" + product.id}>{product.name}</a></li>
{/each}
</ul>
Product Details:产品详情:
<script>
export let params = {};
$: id = params.id;
$: name = params.name;
</script>
<h1>Product Details</h1>
<p>Name: {name}</p>
<p>ID: {id}</p>
<p><a href="#/products/">Back to the list of products</a></p>
Products ProductDetails产品ProductDetails
I got the ID from the URl and wanted to also get the name by the ID.我从 URl 获得了 ID,还想通过 ID 获取名称。 However, I don't know how I might be able to do that.
但是,我不知道我怎么能做到这一点。
Usually your products would be stored in some database and the details page makes a request to get the product details using the ID.通常您的产品会存储在某个数据库中,详细信息页面会请求使用 ID 获取产品详细信息。 If the user opens the product details page directly (eg from a shared link), there will be no "previous page", so you should not rely on passing data from it.
如果用户直接打开产品详细信息页面(例如从共享链接),将不会有“上一页”,因此您不应依赖从中传递数据。
If you just want to set it up for testing, then extract the products list object into a separate module so it can be imported on the details page so you can search for the product via the ID.如果你只是想设置它来测试,然后将产品列表 object 提取到一个单独的模块中,以便在详细信息页面上导入它,以便你可以通过 ID 搜索产品。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.