Logo
Section 1 / 7

动态路由简介

学习如何使用动态路由来程序化生成页面。

导入

动态路由简介

学习如何使用动态路由来程序化生成页面。

表格

文件生成的路由
src/pages/index.astrodomain.com/
src/pages/contact.astrodomain.com/contact
src/pages/contact/index.astrodomain.com/contact
src/pages/contact/john.astrodomain.com/contact/john

表格

路由使用静态路由所需的文件使用动态路由所需的文件
/post/introsrc/pages/post/intro.astrosrc/pages/post/[post].astro
/post/routessrc/pages/post/routes.astrosrc/pages/post/[post].astro
/post/wrapping-upsrc/pages/post/wrapping-up.astrosrc/pages/post/[post].astro
1// 使用 [post].astro 作为文件名: 2export function getStaticPaths() { 3 return [ 4 { params: { post: 'latest' }}, // post 属性名称与文件名一致 5 { params: { post: 'first-post' }}, 6 { params: { post: 'second-post' }}, 7 ]; 8} 9 10// 使用 [author].astro 作为文件名: 11export function getStaticPaths() { 12 return [ 13 { params: { author: 'latest' }}, // author 属性名称与文件名一致 14 { params: { author: 'first-post' }}, 15 { params: { author: 'second-post' }}, 16 ]; 17}
1export function getStaticPaths() { 2 return [ 3 { params: { post: 'astro-series/intro' }}, 4 { params: { post: 'astro-series/components' }}, 5 { params: { post: 'astro-series/finishing-your-project' }}, 6 ]; 7}
1const posts = [ 2 { 3 slug: 'latest', 4 title: '最新文章' 5 }, 6 { 7 slug: 'first-post', 8 title: '第一篇文章' 9 } 10] 11 12export function getStaticPaths() { 13 return posts.map(post => ({ 14 params: { post: post.slug }, 15 props: { 16 post 17 } 18 })) 19} 20 21console.log(getStaticPaths()); 22 23// 在组件中稍后提取属性: 24// const { post } = Astro.props;

附录

动态路由与自定义内容渲染