1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

SvelteKitでパスを取得する

Last updated at Posted at 2023-12-01

URLからパラメータを取得する方法

SvelteKitではURLの一部を変数として扱うことができる。
例えば、src/routes/[slug].svelte というファイルを作成すると、[slug] の部分は何でも良い文字列になる。

仮に、/your-slug-here のようなURLにアクセスすると、your-slug-here が slug の値として取得できる。

load 関数でのパラメータの取得

SvelteKitでは、+page.server.jsファイルを使用してサーバーサイドでページに関連するデータを取得できる。
load 関数は、server.jsファイル内で定義し、ページにアクセスする際、サーバーサイドで実行される。

src/routes/[slug]/+page.server.js
export async function load({ params }) {
  // 'slug' パラメータの取得(異なるパラメータ名の場合は変更が必要)
  const slug = params.slug;

  // 'slug' をクライアントサイドに返す
  return {
      slug  
  };
}

paramsオブジェクトから、URLの動的な部分(例:[slug]、[id]、[name] など)に対応する値を取得できる。

クライアントサイドで受け取る

src/routes/[slug]/+page.svelte
<script>
  // 'data' は +page.server.js から渡される
  export let data;
</script>

<div>
    <!-- propsの中にはいってる -->
  <h1>Slug: {data.props.slug}</h1>
</div>

実際には、取得したパラメーターを使って、データをフェッチ、取得したデータを返すこと多い。

例えばこんな感じ↓

src/routes/[category]/+page.server.js
// 商品データ
const products = [
	{
		id: 1,
		name: 'パスタ',
		price: 1000,
		category: 'pasta',
		description: '美味しいパスタです'
	},
	{
		id: 2,
		name: 'パン',
		price: 600,
		category: 'bread',
		description: '美味しいパンです'
	}
];

// 商品データからカテゴリーに一致する商品を返す関数
const getProducts = (category: string) => {
	return products.filter((product) => product.category === category);
};

export function load({ params }) {
	const category = params.category;
	const filteredProducts = getProducts(category);
	return {
		products: filteredProducts
	};
}

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?