如何安装svelte_如何在svelte中创建路由器

这篇博客介绍了如何安装Svelte,详细步骤来源于官方文档和Medium上的一篇文章,为初学者提供了清晰的指引。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如何安装svelte

斯威特(SVELTE)

In Single Page Applications, for example when we are using a JavaScript framework (as our beloved Svelte), we need to provide a method for our users to navigate between sections of the website as they need.

例如,在单页应用程序中,当我们使用JavaScript框架(如我们钟爱的Svelte)时,我们需要为用户提供一种在他们需要的网站部分之间导航的方法。

Since in SPA all the web page requests are redirected to the root page, we need to simulate the “standard” way of navigating pages. This is where routing libraries help us, and although it seems like a complicated task to reproduce, its base functionality is very simple and can be done in few lines of code.

由于在SPA中,所有网页请求都被重定向到根页面,因此我们需要模拟“标准”的页面导航方式。 这是路由库为我们提供帮助的地方,尽管复制似乎很复杂,但它的基本功能非常简单,可以用几行代码完成。

At the end of the article, we can use our own router, maybe for our next project.

在本文的结尾,我们可以使用自己的路由器,也许用于下一个项目。

为什么要实施自定义路由器 (Why to implement a custom router)

  • We don’t need all the functions of our current router package. The bundle size of an SPA is one of the most important things to consider, because the performance is directly proportional to the time it takes for the user to download the necessary scripts.

    我们不需要当前路由器包的所有功能。 SPA的捆绑包大小是要考虑的最重要的事情之一,因为性能与用户下载必要脚本所花费的时间成正比。

  • We can customize the router functionality to adapt to your needs. Maybe we want to add some transitions between pages, or trigger a function when the page changes, well… We have the control of the code, and we are writing our opinionated rules.

    我们可以自定义路由器功能以适应您的需求。 也许我们想在页面之间添加一些过渡,或者在页面更改时触发一个函数,好吧……我们拥有代码的控制权,并且我们正在编写我们自以为是的规则。

  • We can learn new Javascript skills. In this article, for example, we will use the HTML5 History API, a native API to interact with browser’s history. You will be amazed by how many possibilities there are.

    我们可以学习新的Javascript技能。 例如,在本文中,我们将使用HTML5 History API (原生API)与浏览器的历史记录进行交互。 您会惊讶于有无数种可能性。

路由器如何运作 (How routers work)

Let’s start learning how our favourite routers work. For example, let’s take the svelte-routing npm package.

让我们开始学习我们最喜欢的路由器如何工作。 例如,让我们采用svelte-routing npm软件包。

<Router {url}>
<Route path="blog/:id" component={Post}/>
<Route path="blog" component={Blog}/>
<Route path="about" component={About}/>
<Route path="/" component={Home} />
</Router><script>
import {Router, Route} from "svelte-routing";
import Home from "./routes/Home.svelte";
import About from "./routes/About.svelte";
import Blog from "./routes/Blog.svelte";
import Post from "./routes/Post.svelte"; export let url = "";
</script>

In this package, we declare the initial path (the url variable), pass it to the Router component, and declare all the routes, each one with the path and the component to load. We will write this code in the main App.svelte, so when the user is requesting a specific page, we always pass in the root page and return the component/page he chooses.

在此程序包中,我们声明初始路径( url变量),将其传递给Router组件,并声明所有路由,每个路由都包含要加载的路径和组件。 我们将在主App.svelte中编写此代码,因此,当用户请求特定页面时,我们总是传递根页面并返回他选择的组件/页面。

To do this, the Router will read the current window.location and will search in declared routes for the one that matches the same pattern. So, the Router will render the right component.

为此,路由器将读取当前window.location,并在声明的路由中搜索与相同模式匹配的路由。 因此,路由器将渲染正确的组件。

我们将构建的自定义路由器的示例 (Example with the custom router we will build)

In this article, we will build a Router component which you can use in this way:

在本文中,我们将构建一个路由器组件,您可以通过以下方式使用它:

<Router {routes}/><script>
import Router from "@/components/Router.svelte";
import Home from "./routes/Home.svelte";
import About from "./routes/About.svelte";
import Blog from "./routes/Blog.svelte";
import Post from "./routes/Post.svelte"; const routes = {
"blog/:id": () => Post,
"blog": () => Blog,
"about": () => About,
"/": () => Home
};
</script>

如何实现路由器 (How to implement the router)

So let’s start: create a new component, call it Router.svelte. Here we need to render the selected page and search for the right route.

因此,让我们开始:创建一个新组件,将其称为Router.svelte 。 在这里,我们需要呈现选定的页面并搜索正确的路线。

基本路由 (Basic routing)

Imagine you have the following routes:

假设您有以下路线:

  • /blog

    /博客
  • /about

    /关于
  • /user/posts

    /用户/帖子
  • /

    /

First of all, we need a place where to render the current page:

首先,我们需要一个渲染当前页面的地方:

<svelte:component this={component}/>

We also need to declare the component variable and accept the routes object as attribute:

我们还需要声明component变量并接受路由对象作为属性:

let component;
export let
routes = {};

Then, we have to find the right route between ours. Let’s create a function LoadRoute:

然后,我们必须找到我们之间的正确路线。 让我们创建一个函数LoadRoute:

const LoadRoute = path => {
component = routes[path]();
};

To conclude, call this function on mount, passing the current page:

最后,请在安装时调用此函数,并传递当前页面:

onMount(() => {
LoadRoute(location.pathname);
});

And intercept the back action with the following function:

并使用以下功能拦截后退动作:

window.onpopstate = () => LoadRoute(location.pathname);

Complete code:

完整的代码:

<svelte:component this={component}/><script>
import {onMount} from "svelte"; let component;
export let
routes = {}; onMount(() => {
LoadRoute(location.pathname);
});
</script><script context="module">
const LoadRoute = path => {
component = routes[path]();
}; window.onpopstate = () => LoadRoute(location.pathname);
</script>

导航功能 (The navigate function)

To navigate inside our website, we need to implement a function that we will use across the project so we can change the page without reloading.

要浏览我们的网站,我们需要实现一个将在整个项目中使用的功能,以便我们无需重新加载即可更改页面。

Add this to your code:

将此添加到您的代码:

<script context="module">
// previous code export const navigate = path => {
window.history.pushState(null, null, path);
LoadRoute(path);
};
</script>

You can now use the function this way in every component:

现在,您可以在每个组件中以这种方式使用该函数:

<button on:click={() => navigate("/about")}>
About
</button>

路径变量 (Path variables)

Another common thing we find in a router is a path with parameters, let’s say we have a blog post that has to respond at /blog/my-post where my-post will be dynamic. In this case, the router has to search also in routes with dynamic pieces.

我们在路由器中发现的另一个常见问题是带有参数的路径,假设我们有一个博客帖子,该帖子必须在/ blog / my-post处响应,而my-post将是动态的。 在这种情况下,路由器还必须搜索具有动态片段的路由。

For example, we can add the following route to our routes:

例如,我们可以将以下路线添加到路线中:

  • /blog/:id

    / blog /:id

In our router, the variable will be defined by a starting “:”, as svelte-routing does.

在我们的路由器中,变量将以首尾的“:”定义,就像svelte-routing一样。

We have to split all available routes into segments (getRouteSegments function), and then compare each segment with the current path (getRoute).

我们必须将所有可用的路由分成多个段( getRouteSegments函数),然后将每个段与当前路径进行比较( getRoute )。

We will obviously need to extract all the variables in the current path as props (getProps function).

显然,我们将需要提取当前路径中的所有变量作为props( getProps函数)。

Add the following code to our <script context=”module”>:

将以下代码添加到我们的<script context =“ module”>:

let _routes = {};const getRouteSegments = routes =>
Object.entries(routes).map(([path, component]) => ({
path,
component,
segments: path
.replace(/^\/+|\/+$/g, '')
.split('/')
.map(segment => ({
name: segment.replace(':', ''),
variable: segment.startsWith(':')
}))
}));const getRoute = path => {
const segments = path.replace(/^\/+|\/+$/g, '').split('/'); return _routes.find(route => {
if(route.segments.length !== segments.length) return false; return segments.every((s, i) =>
route.segments[i].name === s ||
route.segments[i].variable
);
});
};const getProps = (path, routeSegments) => {
let props = {}; const segments = path.replace(/^\/+|\/+$/g, '').split('/');
segments.map((s, i) =>
routeSegments[i].variable &&
(props[routeSegments[i].name] = s)
); return props;
};

Now, we declare the props variable in <script>:

现在,我们在<script>中声明props变量:

let props = {};

We edit our onMount function:

我们编辑onMount函数:

onMount(() => {
_routes = getRouteSegments(routes);
LoadRoute(location.pathname);
});

And our LoadRoute function:

还有我们的LoadRoute函数:

const LoadRoute = async(path) => {
const current = getRoute(path); component = (await current.component()).default;
props = getProps(path, current.segments);
};

Last thing, we have to pass the props to the current component:

最后,我们必须将道具传递给当前组件:

<svelte:component this={component} {...props}/>

完整的Router.svelte代码 (Complete Router.svelte code)

<svelte:component this={component} {...props}/><script>
import {onMount} from "svelte"; let component;
export let
routes = {}; onMount(() => {
_routes = getRouteSegments(routes);
LoadRoute(location.pathname);
});
</script><script context="module">
let _routes = {};
let props = {}; const LoadRoute = async(path) => {
const current = getRoute(path); component = (await current.component()).default;
props = getProps(path, current.segments);
}; const getRouteSegments = routes =>
Object.entries(routes).map(([path, component]) => ({
path,
component,
segments: path
.replace(/^\/+|\/+$/g, '')
.split('/')
.map(segment => ({
name: segment.replace(':', ''),
variable: segment.startsWith(':')
}))
})); const getRoute = path => {
const segments = path.replace(/^\/+|\/+$/g, '').split('/'); return _routes.find(route => {
if(route.segments.length !== segments.length) return false; return segments.every((s, i) =>
route.segments[i].name === s ||
route.segments[i].variable
);
});
}; const getProps = (path, routeSegments) => {
let props = {}; const segments = path.replace(/^\/+|\/+$/g, '').split('/');
segments.map((s, i) =>
routeSegments[i].variable &&
(props[routeSegments[i].name] = s)
); return props;
}; export const navigate = path => {
window.history.pushState(null, null, path);
LoadRoute(path);
}; window.onpopstate = () => LoadRoute(location.pathname);
</script>

结论 (Conclusions)

This is my first article on Medium, I hope to write many other articles and help you. I’ll write about my experiences as a web developer and the new technologies I’ll use.

这是我关于Medium的第一篇文章,希望能写很多其他文章并为您提供帮助。 我将介绍我作为Web开发人员的经验以及将要使用的新技术。

I’m sorry if I’ll do some grammatical errors but English is not my native language.

抱歉,如果我会出现一些语法错误,但是英语不是我的母语。

If I helped you or you have any questions, please contact me and maybe follow me for other tips. Thank you all!

如果我为您提供帮助或有任何疑问,请与我联系,或者跟随我获取其他提示。 谢谢你们!

Here are some of my other articles:

这是我的其他一些文章:

普通英语JavaScript (JavaScript In Plain English)

Enjoyed this article? If so, get more similar content by subscribing to Decoded, our YouTube channel!

喜欢这篇文章吗? 如果是这样,请订阅我们的YouTube频道解码,以获得更多类似的内容

翻译自: https://medium.com/javascript-in-plain-english/how-to-create-a-router-in-svelte-ce66c10275fe

如何安装svelte

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值