页面数据加载通常位于+page.server.ts
中,如何在其中获取 url 各种信息?下面是具体介绍:
In SvelteKit’s +page.server.ts
(or +page.ts
), the load
function receives a context object that contains everything you need to access URL arguments.
There are two main types of URL arguments:
- Path Parameters: Defined in your file-based routing (e.g.,
[slug]
,[id]
). - Query Parameters: Appended to the URL after a
?
(e.g.,?query=searchterm&page=2
).
Let’s break down how to get both.
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ params, url }) => {
// 1. Accessing Path Parameters (from your route structure)
// Example route: src/routes/blog/[slug]/+page.server.ts
// URL example: /blog/my-awesome-post
const slug = params.slug;
console.log('Path Parameter (slug):', slug); // e.g., 'my-awesome-post'
// Example route: src/routes/products/[category]/[productId]/+page.server.ts
// URL example: /products/electronics/12345
// const category = params.category;
// const productId = params.productId;
// console.log('Category:', category); // e.g., 'electronics'
// console.log('Product ID:', productId); // e.g., '12345'
// 2. Accessing Query Parameters (from the URL's search string)
// URL example: /blog/my-awesome-post?author=JohnDoe&version=draft&tags=svelte&tags=kit
const author = url.searchParams.get('author');
console.log('Query Parameter (author):', author); // e.g., 'JohnDoe'
const version = url.searchParams.get('version');
console.log('Query Parameter (version):', version); // e.g., 'draft'
// If a query parameter can appear multiple times (e.g., ?tags=svelte&tags=kit)
const tags = url.searchParams.getAll('tags');
console.log('Query Parameters (tags):', tags); // e.g., ['svelte', 'kit']
// To check if a parameter exists
const hasFeatureFlag = url.searchParams.has('feature');
console.log('Has feature flag:', hasFeatureFlag);
// You can also iterate over all search parameters
for (const [key, value] of url.searchParams.entries()) {
console.log(`All query params - ${key}: ${value}`);
}
// You typically return an object from load, which will then be available
// to your +page.svelte component via `data`.
return {
slug,
author,
version,
tags,
hasFeatureFlag,
// ... any data fetched from a database or API
postContent: `This is the content for ${slug || 'unknown post'} by ${author || 'anonymous'}.`
};
};
Explanation:
{ params, url }
: This is destructuring the context object that SvelteKit passes to yourload
function.params
: An object containing all the path parameters defined in your file-based routing. For a route likesrc/routes/blog/[slug]/+page.server.ts
,params
will have aslug
property.url
: AURL
object (similar to the browser’swindow.location
) that provides detailed information about the current URL.
url.searchParams
: This is aURLSearchParams
object, which is part of the standard Web API. It provides convenient methods for working with URL query strings..get('paramName')
: Returns the value of the first occurrence of the specified query parameter..getAll('paramName')
: Returns an array of all values for the specified query parameter (useful if a parameter can appear multiple times, like?tags=a&tags=b
)..has('paramName')
: Returnstrue
if the specified query parameter exists,false
otherwise.- You can also iterate over
url.searchParams.entries()
,keys()
, orvalues()
if you need to process all of them dynamically.
How to use it in +page.svelte
:
After your +page.server.ts
returns the data, you can access it in your +page.svelte
component:
<!-- src/routes/blog/[slug]/+page.svelte -->
<script lang="ts">
import type { PageData } from './$types';
// SvelteKit automatically makes the data returned from `load` available
// via the `data` prop.
export let data: PageData;
// You can destructure it directly
const { slug, author, version, tags, postContent } = data;
</script>
<h1>{postContent}</h1>
<p>Slug: {slug}</p>
{#if author}
<p>Author: {author}</p>
{/if}
{#if version}
<p>Version: {version}</p>
{/if}
{#if tags && tags.length > 0}
<p>Tags: {tags.join(', ')}</p>
{/if}
This setup provides a robust and clear way to handle all types of URL arguments in your SvelteKit server-side load
functions.