如何在Astro中实现类vue-router的动态路由页面导航
在Astro中实现列表页到动态详情页的导航方案
1. 动态路由配置步骤
- 列表页跳转逻辑:在
list.astro(即你的listPage)中,遍历从API获取的产品列表,给每个产品卡片添加跳转链接。直接使用HTML原生<a>标签即可,路径拼接产品ID:--- // list.astro 顶部脚本区 const products = await fetch('你的API地址').then(res => res.json()); --- <main> {products.map(product => ( <a href={`/products/${product.id}`} class="product-card"> <h3>{product.name}</h3> <!-- 其他产品信息 --> </a> ))} </main> - 详情页参数获取:在动态详情页
[id].astro(即你的idPage)中,通过Astro.params.id拿到当前页面的产品ID,再请求API获取对应详情:--- // [id].astro 顶部脚本区 const { id } = Astro.params; const product = await fetch(`你的API地址/${id}`).then(res => res.json()); --- <main> <h1>{product.name}</h1> <!-- 产品详情内容 --> </main>
2. 支持动态路由的文件结构
遵循Astro的路由约定,建议采用如下文件结构:
src/ ├── pages/ │ ├── list.astro # 列表页,对应路由 /list │ └── products/ │ └── [id].astro # 动态详情页,匹配 /products/任意ID 路由 ├── components/ │ └── ProductCard.astro # 可选:抽离产品卡片为独立组件,复用代码 └── utils/ └── fetchProducts.js # 可选:抽离数据获取逻辑,列表页和详情页复用
- Astro会自动把
pages目录下的文件映射为路由,products/[id].astro这种方括号命名的文件就是动态路由,方括号里的id会作为路由参数被捕获。
3. 推荐的最佳实践
- 预渲染静态页面:如果产品数据是静态或可提前获取的,在
[id].astro中使用getStaticPaths预生成所有详情页,提升访问速度和SEO表现:--- export async function getStaticPaths() { const products = await fetch('你的API地址').then(res => res.json()); return products.map(product => ({ params: { id: product.id.toString() }, props: { product } // 直接传递产品数据,避免重复请求 })); } const { product } = Astro.props; --- - 错误处理:在详情页添加ID不存在的判断,返回404页面:
--- const { id } = Astro.params; const res = await fetch(`你的API地址/${id}`); if (!res.ok) { return Astro.redirect('/404', 302); // 或者直接渲染404内容 } const product = await res.json(); --- - 组件复用:把产品卡片的UI抽成
ProductCard.astro组件,接受product作为props,减少重复代码:<!-- components/ProductCard.astro --> --- export interface Props { product: { id: string; name: string; /* 其他字段 */ }; } const { product } = Astro.props; --- <a href={`/products/${product.id}`} class="product-card"> <h3>{product.name}</h3> <!-- 统一的卡片样式和内容 --> </a> - 客户端导航优化:如果需要无刷新跳转,安装并使用
@astrojs/navigation的<Link>组件替代原生<a>标签,提升交互体验:import { Link } from '@astrojs/navigation'; <Link href={`/products/${product.id}`}> <!-- 卡片内容 --> </Link> - 数据逻辑复用:把API请求逻辑抽离到
utils/fetchProducts.js中,列表页和详情页都调用同一个函数,避免代码冗余。
内容的提问来源于stack exchange,提问作者Michael Luo
相关产品推荐
相关产品推荐

