SvelteKit问题:如何根据用户选择跳转路由并加载分类数据?
解决SvelteKit动态路由传参与数据加载问题
思路确认
你的整体思路没问题:通过下拉选择分类ID,提交后跳转至动态路由/category/[num],再根据路由参数加载对应分类的随机名言,完全符合SvelteKit的路由设计逻辑。
步骤1:修改首页表单,实现跳转传参
当前表单缺少提交后的跳转逻辑,修改/routes/+page.svelte的表单代码,让选择分类后跳转到对应动态路由:
<script> export let categories; let selectedCategory = ''; import { goto } from '$app/navigation'; function handleSubmit(e) { e.preventDefault(); if (selectedCategory) { goto(`/category/${selectedCategory}`); } } </script> <form on:submit={handleSubmit}> <label for="category">Select a category below:</label> <select name="category" id="category" bind:value={selectedCategory} required > <option value="" disabled selected>Select...</option> {#each categories as category (category.id)} <option value={category.id}>{category.name}</option> {/each} </select> <button type="submit">Get Help</button> </form>
步骤2:编写动态路由的+page.server.js,加载分类名言
在/routes/category/[num]/+page.server.js中,获取路由参数并从Supabase查询对应分类的随机名言:
import { supabase } from '$lib/supabase'; // 替换为你的Supabase实例路径 export async function load({ params }) { const categoryId = parseInt(params.num); if (!categoryId) return { quote: null }; // 根据你的表结构调整,示例假设名言表名为quotes,关联字段为category_id const { data: quotes, error } = await supabase .from('quotes') .select('*') .eq('category_id', categoryId) .order('random()') .limit(1); if (error) { console.error(error); return { quote: null }; } return { quote: quotes?.[0] || null }; }
步骤3:编写动态路由的+page.svelte,展示名言
在/routes/category/[num]/+page.svelte中,接收并展示数据:
<script> export let data; </script> <div class="quote-wrapper"> {#if data.quote} <blockquote>{data.quote.content}</blockquote> <p class="quote-author">{data.quote.author || 'Anonymous'}</p> {:else} <p>No quotes available for this category.</p> {/if} </div>
排查提示
- 确保Supabase实例初始化正确,
$lib/supabase.js中的密钥、URL配置无误 - 检查名言表的
category_id字段类型,需与分类表的id类型匹配(如均为整数) - 若路由参数解析异常,可在
load函数中打印params.num确认参数格式
内容的提问来源于stack exchange,提问作者SH2323
相关产品推荐
相关产品推荐

