【Svelte】如何获取 url 信息?

发布于:2025-09-10 ⋅ 阅读:(16) ⋅ 点赞:(0)

页面数据加载通常位于+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:

  1. Path Parameters: Defined in your file-based routing (e.g., [slug], [id]).
  2. 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:

  1. { params, url }: This is destructuring the context object that SvelteKit passes to your load function.
    • params: An object containing all the path parameters defined in your file-based routing. For a route like src/routes/blog/[slug]/+page.server.ts, params will have a slug property.
    • url: A URL object (similar to the browser’s window.location) that provides detailed information about the current URL.
  2. url.searchParams: This is a URLSearchParams 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'): Returns true if the specified query parameter exists, false otherwise.
    • You can also iterate over url.searchParams.entries(), keys(), or values() 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.


网站公告

今日签到

点亮在社区的每一天
去签到