Skip to main content
Svelte基础
介绍
响应
属性Props
逻辑表达式
事件
绑定
Classes和样式
动作Actions
转场
Svelte高阶
响应式进阶
内容复用
动画
高级绑定
高级转场
上下文API
特殊元素
脚本模块
接下来
SvelteKit基础
介绍
路由
加载数据
Headers和cookies
Shared modules
Forms
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Hooks
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion

有时候路由可能并不确定,是动态的。比如一个博客网站,用户可以访问/blog/one, /blog/two, /blog/three 获取不同的博客内容。我们总不能有多少博客就写多少文件吧?!这时我们可以使用路由参数——一对方括号夹个变量名。 比如 src/routes/blog/[slug]/+page.svelte. 其中[slug]就是路由参数。 可以在页面中获取参数值,这里可能是one,two,there, ...其中一个, 然后再返回相应博客内容。新增文件src/routes/blog/[slug]/+page.svelte:

To create routes with dynamic parameters, use square brackets around a valid variable name. For example, a file like src/routes/blog/[slug]/+page.svelte will create a route that matches /blog/one, /blog/two, /blog/three and so on. Let’s create that file:

src/routes/blog/[slug]/+page
<h1>blog post</h1>

下个练习我们再展示怎么根据参数值展示相应的博客内容。

We can now navigate from the /blog page to individual blog posts. In the next chapter, we’ll see how to load their content.

偷偷的告诉你:一个URl节点里还能包含多个路由参数,只要它们之间有个静态内容分割就行。比如foo/[bar]x[baz]其中[bar][baz]都是动态参数.

Multiple route parameters can appear within one URL segment, as long as they are separated by at least one static character: foo/[bar]x[baz] is a valid route where [bar] and [baz] are dynamic parameters.

Edit this page on GitHub

1
2
<p>home</p>