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

路由 (Routes)就是决定应用如何根据URL向用户展示相应的内容。
SvelteKit使用基于 文件系统 的路由,也就说代码中的文件组织形式直接关系到其对应的访问URL。
每个src/routes下的+page.svelte的文件,就是一个页面. 当前只有src/routes/+page.svelte对应/. 如果我们使用/about访问就会报404页面找不到错误.
小主可以通过添加src/routes/about/+page.svelte文件修复这个问题:

SvelteKit uses filesystem-based routing, which means that the routes of your app — in other words, what the app should do when a user navigates to a particular URL — are defined by the directories in your codebase. Every +page.svelte file inside src/routes creates a page in your app. In this app we currently have one page — src/routes/+page.svelte, which maps to /. If we navigate to /about, we’ll see a 404 Not Found error.

Let’s fix that. Add a second page, src/routes/about/+page.svelte, copy the contents of src/routes/+page.svelte, and update it:

src/routes/about/+page
<nav>
	<a href="/">home</a>
	<a href="/about">about</a>
</nav>

<h1>about</h1>
<p>this is the about page.</p>

现在小主就可以使用//about访问了

We can now navigate between / and /about.

与传统的多页应用不同,导航到 /about 并返回会像单页应用一样更新当前页面的内容。这让我们兼顾了两者的优势——快速的服务器渲染启动和即时导航。(此行为可以配置。)

Unlike traditional multi-page apps, navigating to /about and back updates the contents of the current page, like a single-page app. This gives us the best of both worlds — fast server-rendered startup, then instant navigation. (This behaviour can be configured.)

Edit this page on GitHub

1
2
3
4
5
6
7
8
<nav>
	<a href="/">home</a>
	<a href="/about">about</a>
</nav>
 
<h1>home</h1>
<p>this is the home page.</p>