SvelteKit中始终访问相同文件的可变路由

huangapple go评论53阅读模式
英文:

Variable Routes in SvelteKit that Always Hit the Same File

问题

我一直在阅读SvelteKit文档的高级路由部分,但我不能完全弄清楚如何做某事。

我希望所有路由都能访问相同的 +page.server.ts 文件:

import type { PageServerLoad } from '../$types';

export const load = (async ({ params }) => {
  console.log('Logging in +page.server.ts');

  console.log(params);
}) satisfies PageServerLoad;

/a/b/c 应该记录:

{
  first: 'a',
  second: 'b',
  third: 'c'
}

/a/b 应该记录:

{
  first: 'a',
  second: 'b',
  third: ''
}

/a 应该记录:

{
  first: 'a',
  second: '',
  third: ''
}

我认为我的文件夹结构应该如下所示:

/routes
- /first
- /first/second
- /first/second/third

但我需要它们都是可选的,并且始终访问/routes内的+page.server.ts

英文:

I've been reading the advanced routing section of the SvelteKit docs, and I can't quite figure out how to do something.

I want all routes to hit the same +page.server.ts file:

import type { PageServerLoad } from '../$types';

export const load = (async ({ params }) => {
  console.log('Logging in +page.server.ts');

  console.log(params);
}) satisfies PageServerLoad;

/a/b/c should log:

{
  first: 'a',
  second: 'b',
  third: 'c'
}

/a/b should log:

{
  first: 'a',
  second: 'b',
  third: ''
}

/a should log:

{
  first: 'a',
  second: '',
  third: ''
}

I think my folder structure should look like this:

/routes
- /first
- /first/second
- /first/second/third

But I need them all to be (optional) and always hit the +page.server.ts inside /routes.

How can I accomplish this?

答案1

得分: 1

如果您希望将某些内容应用于所有路由,请将其设为布局,因此在这种情况下是 +layout.server.ts

可选参数使用 [[parameter]],因此您会得到 routes/[[first]]/[[second]]/[[third]]

但是,如果未设置它们,它们将不会出现在 params 中,因此如果您想要一个默认值,例如空字符串,您需要在代码中自行设置。

const resolved = {
  first: '',
  second: '',
  third: '',
  ...params,
};
console.log(resolved)
英文:

If you want something to apply to all routes, make it a layout, so in this case +layout.server.ts.

Optional parameters use [[parameter]], so you get routes/[[first]]/[[second]]/[[third]].

But they do not appear in params if not set, so if you want a default like an empty string you have to set that yourself in code.

const resolved = {
	first: '',
	second: '',
	third: '',
	...params,
};
console.log(resolved)

huangapple
  • 本文由 发表于 2023年6月9日 10:55:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76436910.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定