跳转到内容

API 参考

Astro global 在 .astro 文件的所有上下文中都可用。它具有以下功能:

Astro.glob() 可以在静态网站 setup 中加载本地文件:

src/components/my-component.astro
---
const posts = await Astro.glob('../pages/post/*.md'); // 返回位于 ./src/pages/post/*.md 的数组并存储在常量 posts 中
---
<div>
{posts.slice(0, 3).map((post) => (
<article>
<h1>{post.frontmatter.title}</h1>
<p>{post.frontmatter.description}</p>
<a href={post.frontmatter.url}>Read more</a>
</article>
))}
</div>

.glob() 只需要一个参数:你想导入的本地文件相对 glob URL。它是异步的并返回数组,这个数组包含匹配文件的导出内容。

.glob() 不接受使用变量或字符串进行插值,因为它们不是静态可分析的。(参见故障排查以了解解决方法)。这是因为 Astro.glob() 是 Vite 的 import.meta.glob() 的包装器。

使用 Astro.glob() 加载的 Markdown 文件返回以下 MarkdownInstance 接口:

export interface MarkdownInstance<T extends Record<string, any>> {
/* 在此文件的 YAML frontmatter 中指定的任何数据 */
frontmatter: T;
/* 该文件的文件绝对路径 */
file: string;
/* 该文件的渲染路径 */
url: string | undefined;
/* 渲染此文件内容的 Astro 组件 */
Content: AstroComponentFactory;
/** (仅限 Markdown) Markdown 文件的原始内容,不包括布局 HTML 和 YAML frontmatter */
rawContent(): string;
/* (仅限 Markdown) Markdown 文件编译后的 HTML,不包括布局 HTML */
compiledContent(): string;
/* 返回该文件中 h1...h6 元素数组的函数 */
getHeadings(): Promise<{ depth: number; slug: string; text: string }[]>;
default: AstroComponentFactory;
}

你可以选择使用 TypeScript 泛型指定 frontmatter 变量类型:

---
interface Frontmatter {
title: string;
description?: string;
}
const posts = await Astro.glob<Frontmatter>('../pages/post/*.md');
---
<ul>
{posts.map(post => <li>{post.frontmatter.title}</li>)}
</ul>

Astro 文件具有以下接口:

export interface AstroInstance {
/* 此文件的文件路径 */
file: string;
/* 此文件的 URL(如果它在 pages 目录中)*/
url: string | undefined;
default: AstroComponentFactory;
}

其他文件可能有各种不同的接口,但如果你不知道文件类型包含什么,那么 Astro.glob() 可以接受 TypeScript 泛型。

---
interface CustomDataFile {
default: Record<string, any>;
}
const data = await Astro.glob<CustomDataFile>('../data/**/*.js');
---

Astro.props 是一个包含任何作为组件属性传递的值的对象。.md.mdx 文件的布局组件接收作为参数的 frontmatter 值。

src/components/Heading.astro
---
const { title, date } = Astro.props;
---
<div>
<h1>{title}</h1>
<p>{date}</p>
</div>
src/pages/index.astro
---
import Heading from '../components/Heading.astro';
---
<Heading title="我的第一篇文章" date="09 Aug 2022" />
进一步了解关于 Markdown 和 MDX 布局 如何处理 props 的内容。
了解如何为你的 props 添加 TypeScript 类型定义 的内容。

Astro.params 是一个包含与此请求匹配的动态路由段的值的对象。

在静态构建中,这将是 getStaticPaths() 返回的params,用于预渲染动态路由.。

在 SSR 构建中,这可以是与动态路由模式中的路径段匹配的任何值。

src/pages/posts/[id].astro
---
export function getStaticPaths() {
return [
{ params: { id: '1' } },
{ params: { id: '2' } },
{ params: { id: '3' } }
];
}
const { id } = Astro.params;
---
<h1>{id}</h1>

另见:params

类型:Request

Astro.request 是标准的 Request 对象。它可以用来获取请求的 urlheadersmethod,甚至是 body。可以使用 new URL(Astro.request.url) 来获得链接对象。

<p>Received a {Astro.request.method} request to "{Astro.request.url}".</p>
<p>Received request headers: <code>{JSON.stringify(Object.fromEntries(Astro.request.headers))}</code>

另见:Astro.url

类型:ResponseInit & { readonly headers: Headers }

Astro.response 是标准的 ResponseInit 对象,它具有以下结构:

  • status:响应的状态码,例如 200
  • statusText:响应状态码与之相对应的状态信息,例如 OK
  • headers:一个能让你为响应设置 HTTP 头部的 Headers 实例。

所以 Astro.response 也用于设置页面响应的 statusstatusTextheaders

---
if(condition) {
Astro.response.status = 404;
Astro.response.statusText = 'Not found';
}
---

或者设置 header:

---
Astro.response.headers.set('Set-Cookie', 'a=b; Path=/;');
---

类型:AstroCookies

添加于: astro@1.4.0

Astro.cookies 包含用于在服务端渲染模式下读取和操作 cookie 的工具方法。

类型:(key: string, options?: AstroCookieGetOptions) => AstroCookie | undefined

获取 AstroCookie 对象形式的 cookie,该对象包含value和用于将 cookie 转换为非字符串类型的工具方法。

类型:(key: string, options?: AstroCookieGetOptions) => boolean

用于判断 cookie 是否存在。如果这个 cookie 已经通过Astro.cookies.set()设置,这将返回 true,否则它将检查 Astro.request 中的 cookies。

类型:(key: string, value: string | object, options?: AstroCookieSetOptions) => void

将 cookie key 设置为给定的值。这将试图把 cookie 的值转换为一个字符串。选项提供了设置 cookie 功能的方法,例如 maxAgehttpOnly

类型:(key: string, options?: AstroCookieDeleteOptions) => void

通过设置过去的到期日期(Unix 时间为 0)使 cookie 失效。

一旦 Cookie 被“删除”(过期),Astro.cookies.has() 将返回 falseAstro.cookies.get() 将返回一个 valueundefinedAstroCookie。删除 Cookie 时可用的选项包括:domainpathhttpOnlysameSitesecure

类型:(cookies: AstroCookies) => void

将新的 AstroCookies 实例合并到当前实例中。任何新的 cookie 将被添加到当前实例中,任何具有相同名称的 cookie 将覆盖现有值。

类型:() => Iterator<string>

获取将与响应一起发送的 Set-Cookie 的 header 的值。

通过 Astro.cookies.get() 获取 cookie 返回一个 AstroCookie 类型。它具有以下结构。

类型:string

cookie 的原始字符串值。

类型:() => Record<string, any>

通过 JSON.parse() 解析 cookie 值,返回一个对象。如果 cookie 值不是有效的 JSON,则抛出异常。

类型:() => number

将 cookie 值解析为数字。如果不是有效数字,则返回 NaN。

类型:() => boolean

转换 cookie 的值为 boolean 类型。

添加于: astro@4.1.0

获取 cookie 允许通过 AstroCookieGetOptions 接口指定选项:

类型:(value: string) => string

允许自定义如何将 cookie 反序列化为值。

添加于: astro@4.1.0

通过 Astro.cookies.set() 设置 cookie,允许传入 AstroCookieSetOptions 来自定义 cookie 如何被序列化。

类型:string

指定域。如果未设置域,则大多数客户端将解释为应用于当前域。

类型:Date

指定 cookie 过期日期。

类型:boolean

如果为 true,则客户端将无法访问该 Cookie。

类型:number

以秒为单位指定 cookie 有效的时间。

类型:string

指定应用 cookie 的域的子路径。

类型:boolean | 'lax' | 'none' | 'strict'

指定 SameSite cookie header 的值。

类型:boolean

如果为 true,则该 Cookie 仅在 https 网站上设置。

类型:(value: string) => string

允许自定义 cookie 序列化方式。

类型:(path: string, status?: number) => Response

允许你重定向到另一个页面,并可选地提供一个 HTTP 响应状态码 作为第二个参数。

页面(而不是子组件)必须 return Astro.redirect() 的结果,以便重定向发生。

对于静态生成的网站,这将使用 <meta http-equiv="refresh"> 标签 实现客户端重定向,并且不支持状态码。

使用按需渲染模式时,支持状态码。除非指定其他代码,否则 Astro 将以默认的 HTTP 302 响应状态码实现重定向请求。

以下示例将用户重定向到登录页面:

src/pages/account.astro
---
import { isLoggedIn } from '../utils';
const cookie = Astro.request.headers.get('cookie');
// 如果用户未登录,则将其重定向到登录页面
if (!isLoggedIn(cookie)) {
return Astro.redirect('/login');
}
---

类型:(rewritePayload: string | URL | Request) => Promise<Response>

添加于: astro@4.13.0

允许你从不同的 URL 或路径提供内容,而不会将浏览器重定向到新页面。

该方法接受字符串、URLRequest 作为路径的位置。

使用字符串提供一个明确的路径:

src/pages/index.astro
---
return Astro.rewrite("/login")
---

当你需要构造重写的 URL 路径时,使用 URL 类型。以下示例通过从相对路径 "../" 创建一个新的 URL 来呈现页面的父路径:

src/pages/blog/index.astro
---
return Astro.rewrite(new URL("../", Astro.url))
---

使用 Request 类型完全控制发送到新路径的 Request。以下示例发送一个请求来渲染父页面,同时提供标头:

src/pages/blog/index.astro
---
return Astro.rewrite(new Request(new URL("../", Astro.url), {
headers: {
"x-custom-header": JSON.stringify(Astro.locals.someValue)
}
}))
---

类型:URL

添加于: astro@1.0.0-rc

由当前 Astro.request.url 的链接字符串值构造的 URL对象。对于与请求链接的某些属性进行交互很有用,例如 pathname 和 origin。

相当于 new URL(Astro.request.url)

如果 site 未配置为静态站点或者使用 serverhybrid 输出的按需渲染站点,Astro.url 在开发模式下将是 localhost

<h1>当前链接是:{Astro.url}</h1>
<h1>当前链接路径名是:{Astro.url.pathname}</h1>
<h1>当前链接源是:{Astro.url.origin}</h1>

你也可以使用 Astro.url 来创建新的链接,并把它作为参数传给 new URL()

src/pages/index.astro
---
// 示例:使用你的生产域名构建一个规范的URL
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
// 示例:使用你目前的域名构建一个用于 SEO meta 标签的URL
const socialImageURL = new URL('/images/preview.png', Astro.url);
---
<link rel="canonical" href={canonicalURL} />
<meta property="og:image" content={socialImageURL} />

类型:string

添加于: astro@1.0.0-rc

指定请求的 IP 地址。这个属性只在为 SSR(服务器端渲染)构建时可用,不应该用于静态网站。

---
const ip = Astro.clientAddress;
---
<div>你的 IP 地址是:<span class="address">{ ip }</span></div>

类型:URL | undefined

Astro.site 返回根据 Astro 配置中的 site 生成的 URL。如果未定义 Astro 配置中的 siteAstro.site 也不会被定义。

类型:string

添加于: astro@1.0.0

Astro.generator 是个便捷方法,它可以添加与你当前 Astro 版本一致的 <meta name="generator"> 标签。它遵循的格式是 "Astro v1.x.x"

<html>
<head>
<meta name="generator" content={Astro.generator} />
</head>
<body>
<footer>
<p><a href="https://astro.build">{Astro.generator}</a> 构建</p>
</footer>
</body>
</html>

Astro.slots 包含修改 Astro 组件插槽的工具函数。

类型:(slotName: string) => boolean

你可以使用 Astro.slots.has() 检查特定插槽名称的内容是否存在。当你想要包装插槽内容,但只想在使用插槽时呈现包装器元素时,这会很有用。

src/pages/index.astro
---
---
<slot />
{Astro.slots.has('more') && (
<aside>
<h2>More</h2>
<slot name="more" />
</aside>
)}

类型:(slotName: string, args?: any[]) => Promise<string>

你可以使用 Astro.slots.render() 将插槽的内容异步渲染为 HTML 字符串。

---
const html = await Astro.slots.render('default');
---
<Fragment set:html={html} />

Astro.slots.render() 还可以接受第二个参数:一个参数数组,该参数数组将被转发给任何函数子组件。这对于自定义实用程序组件很有用。

举个例子,这个 <Shout /> 组件将它的 message 属性转换为大写,并将其传递给默认插槽:

src/components/Shout.astro
---
const message = Astro.props.message.toUpperCase();
let html = '';
if (Astro.slots.has('default')) {
html = await Astro.slots.render('default', [message]);
}
---
<Fragment set:html={html} />

作为 <Shout /> 的子级传递的回调函数将会接收到大写的 message 参数:

src/pages/index.astro
---
import Shout from "../components/Shout.astro";
---
<Shout message="slots!">
{(message) => <div>{message}</div>}
</Shout>
<!-- 渲染成 <div>SLOTS!</div> -->

回调函数可以传递给带有 slot 属性并包装着 HTML 元素标签的具名插槽。这个元素仅用于将回调传递给具名插槽,而不会被渲染到页面上。

<Shout message="slots!">
<fragment slot="message">
{(message) => <div>{message}</div>}
</fragment>
</Shout>

使用标准的 HTML 元素作为包装标签,或者使用任何小写标签(例如 <fragment> 而不是 <Fragment />),这些标签不会被解释为组件。不要使用 HTML 的 <slot> 元素,因为它会被解释为 Astro 插槽。

Astro.self 允许 Astro 组件被递归调用。这使得你可以通过在组件模板中使用 <Astro.self> 从自身内部渲染 Astro 组件。这对遍历大型数据存储和嵌套数据结构很有帮助。

NestedList.astro
---
const { items } = Astro.props;
---
<ul class="nested-list">
{items.map((item) => (
<li>
<!-- 如果有嵌套的数据结构,将渲染 `<Astro.self>` -->
<!-- 并可以通过递归调用来传递参数 -->
{Array.isArray(item) ? (
<Astro.self items={item} />
) : (
item
)}
</li>
))}
</ul>

然后,这个组件可以这样用:

---
import NestedList from './NestedList.astro';
---
<NestedList items={['A', ['B', 'C'], 'D']} />

之后将会渲染这样的 HTML:

<ul class="nested-list">
<li>A</li>
<li>
<ul class="nested-list">
<li>B</li>
<li>C</li>
</ul>
</li>
<li>D</li>
</ul>

添加于: astro@2.4.0

Astro.locals 是一个对象,包含来自中间件的 context.locals对象的任何值。使用该对象可访问中间件在你的 .astro 文件中返回的数据。

src/pages/Orders.astro
---
const title = Astro.locals.welcomeTitle();
const orders = Array.from(Astro.locals.orders.entries());
---
<h1>{title}</h1>
<ul>
{orders.map(order => {
return <li>{ /* 每单都有收获 */ }</li>
})}
</ul>

类型:string | undefined

添加于: astro@3.5.0

Astro.preferredLocale 是一个代表当前用户的首选语言环境的计算出的值。

它是通过检查 i18n.locales 数组中配置的语言环境和用户浏览器通过头部 Accept-Language 指定的语言环境来计算的。如果不存在匹配项则该值为 undefined

这个属性只在为 SSR(服务器端渲染)构建时可用,不应该用于静态网站。

类型:string[] | undefined

添加于: astro@3.5.0

Astro.preferredLocaleList 是一个同时被浏览器请求并且你的网站也支持的语言环境的数组。它是一个由你的网站和你的访客共同支持的语言环境的列表。

如果浏览器请求的语言环境没有在你的网站中被支持,那么该值为 []:你不支持你的访客的任何首选语言环境。

如果浏览器没有指定任何首选语言环境,那么该值将是 i18n.locales:你支持的所有语言环境都将被同等视为访客倾向的语言环境。

这个属性只在为 SSR(服务器端渲染)构建时可用,不应该用于静态网站。

类型:string | undefined

添加于: astro@3.5.6

从当前 URL 使用你的 locales 配置中指定的语法计算出的语言环境。如果 URL 不包含 /[locale]/ 前缀,则该值将默认为 i18n.defaultLocale

类型:(action: TAction) => ActionReturnType<TAction> | undefined

添加于: astro@4.15.0

Astro.getActionResult() 是一个返回 Action 提交结果的函数。它接受一个 Action 函数作为参数(例如 actions.logout),当接收到提交时返回一个 dataerror 对象。否则,它将返回 undefined

src/pages/index.astro
---
import { actions } from 'astro:actions';
const result = Astro.getActionResult(actions.logout);
---
<form action={actions.logout}>
<button type="submit">退出登录</button>
</form>
{result?.error && <p>退出登录失败。请再试一次。</p>}

添加于: astro@4.15.0

Astro.callAction() 是一个直接从你的 Astro 组件中调用 Action 处理程序的函数。它接受一个 Action 函数作为第一个参数(例如 actions.logout),以及该 Action 接收的任何输入作为第二个参数。它返回 Action 的结果作为 Promise。

src/pages/index.astro
---
import { actions } from 'astro:actions';
const { data, error } = await Astro.callAction(actions.logout, { userId: '123' });
---

端点函数接收一个上下文对象作为第一个参数。它与许多 Astro 全局属性相似。

endpoint.json.ts
import type { APIContext } from 'astro';
export function GET(context: APIContext) {
// ...
}

context.params 是一个对象,其中包含与此请求匹配的动态路由段的值。

在静态构建中,这将是用于预渲染动态路由getStaticPaths() 返回的 params

在 SSR 构建中,这可以是与动态路由模式中的路径段匹配的任何值。

src/pages/posts/[id].json.ts
import type { APIContext } from 'astro';
export function getStaticPaths() {
return [
{ params: { id: '1' } },
{ params: { id: '2' } },
{ params: { id: '3' } }
];
}
export function GET({ params }: APIContext) {
return new Response(
JSON.stringify({ id: params.id }),
);
}

另见:params

添加于: astro@1.5.0

context.props 是一个对象,其中包含从 getStaticPaths() 传递的任何 props。由于在为 SSR 构建时不使用 getStaticPaths(),因此 context.props 仅在静态构建中可用。

src/pages/posts/[id].json.ts
import type { APIContext } from 'astro';
export function getStaticPaths() {
return [
{ params: { id: '1' }, props: { author: 'Blu' } },
{ params: { id: '2' }, props: { author: 'Erika' } },
{ params: { id: '3' }, props: { author: 'Matthew' } }
];
}
export function GET({ props }: APIContext) {
return new Response(
JSON.stringify({ author: props.author }),
);
}

另见:通过props传递数据

类型:Request

一个标准的 Request 对象。它可以用来获取请求的 urlheadersmethod 甚至是 body

import type { APIContext } from 'astro';
export function GET({ request }: APIContext) {
return new Response(`Hello ${request.url}`);
}

另见:Astro.request

类型:AstroCookies

context.cookies 包含用于读取和操作 cookie 的工具。

另见:Astro.cookies

类型:URL

添加于: astro@1.5.0

context.url 是一个 URL 对象,它是从当前 context.request.url URL 字符串值构造的。

另见:Astro.url

类型:string

添加于: astro@1.5.0

指定请求的 IP 地址。此属性仅在构建 SSR(服务器端渲染)时可用,不应用于静态站点。

import type { APIContext } from 'astro';
export function GET({ clientAddress }: APIContext) {
return new Response(`Your IP address is: ${clientAddress}`);
}

另见:Astro.clientAddress

类型:URL | undefined

添加于: astro@1.5.0

context.site 返回一个由 Astro 配置中的 site 生成的 URL。如果未定义,则将返回从 localhost 生成的 URL。

另见:Astro.site

类型:string

添加于: astro@1.5.0

context.generator 是一个方便的方法,用于指示项目正在运行的 Astro 版本。它遵循 "Astro v1.x.x" 的格式。

src/pages/site-info.json.ts
import type { APIContext } from 'astro';
export function GET({ generator, site }: APIContext) {
const body = JSON.stringify({ generator, site });
return new Response(body);
}

另见:Astro.generator

类型:(path: string, status?: number) => Response

添加于: astro@1.5.0

context.redirect() 返回一个 Response 对象,允许你重定向到另一个页面。此函数仅在构建 SSR(服务器端渲染)时可用,不应用于静态站点。

import type { APIContext } from 'astro';
export function GET({ redirect }: APIContext) {
return redirect('/login', 302);
}

另见:Astro.redirect()

类型:(rewritePayload: string | URL | Request) => Promise<Response>

添加于: astro@4.13.0

允许你从不同的 URL 或路径提供内容,而不会将浏览器重定向到新页面。

该方法接受字符串、URLRequest 作为路径的位置。

使用字符串提供一个明确的路径:

import type { APIContext } from 'astro';
export function GET({ rewrite }: APIContext) {
return rewrite('/login');
}

当你需要构造重写的 URL 路径时,使用 URL 类型。以下示例通过从相对路径 "../" 创建一个新的 URL 来呈现页面的父路径:

import type { APIContext } from 'astro';
export function GET({ rewrite }: APIContext) {
return rewrite(new URL("../", Astro.url));
}

使用 Request 类型完全控制发送到新路径的 Request。以下示例发送一个请求来渲染父页面,同时提供标头:

import type { APIContext } from 'astro';
export function GET({ rewrite }: APIContext) {
return rewrite(new Request(new URL("../", Astro.url), {
headers: {
"x-custom-header": JSON.stringify(Astro.locals.someValue)
}
}));
}

另见:Astro.rewrite()

添加于: astro@2.4.0

context.locals 是一个对象,用于在请求的生命周期内存储和访问任意信息。

中间件函数可以读写context.locals的值:

src/middleware.ts
import type { MiddlewareHandler } from 'astro';
export const onRequest: MiddlewareHandler = ({ locals }, next) => {
if (!locals.title) {
locals.title = "Default Title";
}
return next();
}

API 端点只能从 context.locals中读取信息:

src/pages/hello.ts
import type { APIContext } from 'astro';
export function get({ locals }: APIContext) {
return new Response(locals.title); // "默认标题"
}

另见:Astro.locals

类型: (action: TAction) => ActionReturnType<TAction> | undefined

添加于: astro@4.15.0

context.getActionResult() 是一个函数,用于从你的 Astro 组件中返回 Action 提交结果。它接受一个 Action 函数作为参数(例如 actions.logout),当接收到提交时返回一个 dataerror 对象。否则,它将返回 undefined

另见:Astro.getActionResult()

添加于: astro@4.15.0

context.callAction() 是一个直接从你的 Astro 组件中调用 Action 处理程序的函数。它接受一个 Action 函数作为第一个参数(例如 actions.logout),以及该 Action 接收的任何输入作为第二个参数。它返回 Action 的结果作为 Promise。

另见:Astro.callAction()

类型:(options: GetStaticPathsOptions) => Promise<GetStaticPathsResult> | GetStaticPathsResult

如果页面在文件名中使用动态参数,该组件将需要导出一个 getStaticPaths() 函数。

必须要有该函数,因为 Astro 是静态站点生成器。这意味着整个网站是预构建的。如果 Astro 不知道在构建时生成什么页面,你的用户在访问你的网站时就看不到它。

---
export async function getStaticPaths() {
return [
{ params: { /* 必需 */ }, props: { /* 可选 */ } },
{ params: { ... } },
{ params: { ... } },
// ...
];
}
---
<!-- 你的 HTML 模板在这里 -->

getStaticPaths() 函数应该返回对象数组,以确定哪些路径会被 Astro 预渲染。

每个返回对象的 params 键都会告诉 Astro 要构建什么路由。返回参数必须映射到你的组件文件路径中定义的动态参数和其余参数。

params 被编码到链接中,所以只能由字符串作为值。每个 params 对象的值必须与页面名称中使用的参数一致。

比如说有 src/pages/posts/[id].astro 页面。如果你从这个页面导出 getStaticPaths 并返回以下的路由:

---
export async function getStaticPaths() {
return [
{ params: { id: '1' } },
{ params: { id: '2' } },
{ params: { id: '3' } }
];
}
const { id } = Astro.params;
---
<h1>{id}</h1>

然后 Astro 会在构建时静态地生成 posts/1posts/2posts/3

为了给每个生成的页面传递额外的数据,你也可以在每个返回的路径对象上设置 props 值。与 params 不同的是,props 没有被编码到链接中,所以并不局限于字符串。

例如,假设你根据从远程 API 获取的数据来生成页面。你可以将完整的数据对象传递给 getStaticPaths 中的页面组件。

---
export async function getStaticPaths() {
const data = await fetch('...').then(response => response.json());
return data.map((post) => {
return {
params: { id: post.id },
props: { post },
};
});
}
const { id } = Astro.params;
const { post } = Astro.props;
---
<h1>{id}: {post.name}</h1>

你也可以传递普通数组,这在生成或缓存已知路径列表时可能会有帮助。

---
export async function getStaticPaths() {
const posts = [
{id: '1', category: "astro", title: "API Reference"},
{id: '2', category: "react", title: "Creating a React Counter!"}
];
return posts.map((post) => {
return {
params: { id: post.id },
props: { post }
};
});
}
const {id} = Astro.params;
const {post} = Astro.props;
---
<body>
<h1>{id}: {post.title}</h1>
<h2>Category: {post.category}</h2>
</body>

然后 Astro 将在构建时使用 pages/posts/[id].astro 中的页面组件静态地生成 posts/1posts/2。页面可以使用 Astro.props 引用这些数据。

分页是 Astro 通过 paginate() 函数原生支持网站的常见用例。paginate() 将自动生成数组,从getStaticPaths()返回,为分页集合的每个页面创建一个 URL。页面编号将作为参数传递,而页面数据将作为page道具传递。

export async function getStaticPaths({ paginate }) {
// 用 fetch()、Astro.glob() 等加载你的数据
const response = await fetch(`https://pokeapi.co/api/v2/pokemon?limit=150`);
const result = await response.json();
const allPokemon = result.results;
// 返回包含分页的所有帖子的路由集合
return paginate(allPokemon, { pageSize: 10 });
}
// 如果设置正确,现在页面已经具备了渲染单页所需的一切参数(见下一节)。
const { page } = Astro.props;

paginate():假定文件名为 [page].astro[...page].astropage 参数将是链接中的页数。

  • /posts/[page].astro:会产生 /posts/1/posts/2/posts/3 等链接。
  • /posts/[...page].astro:将产生 /posts/posts/2 /posts/3 等链接。

paginate() 函数具有以下参数:

  • pageSize - 每页显示的项目数(默认为 10
  • params - 用于创建动态路由的附加参数
  • props - 在每个页面上可用的附加属性

分页会给每个渲染的页面传递 page 参数,代表分页集合中的单页数据。这包括你分页的数据(page.data)以及该页的元数据(page.urlpage.startpage.endpage.total 等)。这些元数据对诸如“下一页”按钮或“显示 100 个中前十个”的信息很有用。

类型:Array

data() 中返回当前页面数据数组。

类型:number

当前页第一个项目的索引,从 0 开始(例如,如果 pageSize: 25,第一页该值未 0,第二页为25,以此类推)。

类型:number

当前页面最后一条数据的索引。

类型:number 默认值:10

每个页面有多少条数据。

类型:number

所有数据的总数量。

类型:number

当前页码,从 1 开始。

类型:number

总页数。

类型:string

获取当前页面的链接(对规范链接很有用)。

类型:string | undefined

获取上一页链接(如果在首页,将是undefined)。如果为 base 设置了值,那么需要将 base 路径拼接到链接前面。

类型:string | undefined

获取下一页链接(如果没有更多的页面,将是undefined)。如果为 base 设置了值,那么需要将 base 路径拼接到链接前面。

类型:string | undefined

添加于: astro@4.12.0

获取第一页链接(如果在首页,将是undefined)。 如果为 base 设置了值,那么需要将 base 路径拼接到链接前面。

类型:string | undefined

添加于: astro@4.12.0

获取最后一页链接(如果在最后一页,将是undefined)。如果为 base 设置了值,那么需要将 base 路径拼接到链接前面。

所有 ESM 模块都包含 import.meta 属性。Astro 基于 Vite 增加了 import.meta.env

import.meta.env.SSR 可以用来了解何时在服务器渲染。有时你可能想要不同的逻辑,例如,某个组件应该只在客户端渲染:

export default function () {
return import.meta.env.SSR ? <div class="spinner"></div> : <FancyComponent />;
}

类型:(options: UnresolvedImageTransform) => Promise<GetImageResult>

getImage()函数旨在生成用于在 HTML 之外的其他地方所使用的图像,例如在 API 路由 中。它还允许你创建自定义的 <Image /> 组件。

getImage() 函数接受一个选项对象,其中包含与 Image 组件相同的属性(除了 alt)。

---
import { getImage } from "astro:assets";
import myBackground from "../background.png"
const optimizedBackground = await getImage({src: myBackground, format: 'avif'})
---
<div style={`background-image: url(${optimizedBackground.src});`}></div>

它返回了一个具有以下类型的对象:

type GetImageResult = {
/* 渲染图像所需的附加 HTML 属性(宽度、高度、样式等) */
attributes: Record<string, any>;
/* 已通过校验的参数 */
options: ImageTransform;
/* 传递的原始参数 */
rawOptions: ImageTransform;
/* 生成图像的路径 */
src: string;
srcSet: {
/* 为 srcset 生成值,每个条目都有一个 url 和一个 size */
values: SrcSetValue[];
/* 准备在`srcset`属性中使用的值 */
attribute: string;
};
}

内容集合(astro:content

段落标题 内容集合(astro:content)

添加于: astro@2.0.0

内容集合提供了 API 来配置和查询 src/content/ 中的 Markdown 或 MDX 文档。有关功能和用法示例,请参考内容集合指南

类型:(input: CollectionConfig) => CollectionConfig

defineCollection() 是一个用于在 src/content/config.* 文件中配置集合的工具函数。

src/content/config.ts
import { z, defineCollection } from 'astro:content';
const blog = defineCollection({
type: 'content',
schema: z.object({
title: z.string(),
permalink: z.string().optional(),
}),
});
// 将定义的集合公开给 Astro
// 通过 `collections` 导出
export const collections = { blog };

这个函数接受以下属性:

类型:'content' | 'data'
默认:'content'

添加于: astro@2.5.0

type 是一个字符串,用于定义存储在集合中的条目的类型:

  • 'content' - 用于内容创作格式,如 Markdown (.md)、MDX (.mdx) 或 Markdoc (.mdoc)
  • 'data' - 用于 JSON (.json) 或 YAML (.yaml) 等纯数据格式

类型:ZodType | (context: SchemaContext) => ZodType

schema 是一个可选的 Zod 对象,用于配置集合的文档 frontmatter 的类型和形状。每个值必须使用 Zod 验证器

有关示例请参考 内容集合指南

类型:(collection: string) => ZodEffects<ZodString, { collection, id: string } | { collection, slug: string }>

添加于: astro@2.5.0

在内容配置中使用 reference() 函数来定义从一个集合到另一个集合的关系或 “引用”。该函数接受一个集合名称,并验证内容前置事项或数据文件中指定的条目标识符。

此示例定义了从博客作者到 “作者 “集合的引用,以及到同一 “博客 “集合的相关文章数组的引用:

import { defineCollection, reference, z } from 'astro:content';
const blog = defineCollection({
type: 'content',
schema: z.object({
// 通过 "id "从 "作者 "集合中引用单个作者
author: reference('authors'),
// 按 "slug "从 "blog "集合中引用相关帖子数组
relatedPosts: z.array(reference('blog')),
})
});
const authors = defineCollection({
type: 'data',
schema: z.object({ /* ... */ })
});
export const collections = { blog, authors };

有关示例请参考 内容集合指南.

类型:(collection: string, filter?: (entry: CollectionEntry<collection>) => boolean) => CollectionEntry<collection>[]

getCollection() 是一个函数,用于通过集合名称检索内容集合条目列表。

默认情况下,它返回集合中的所有项目,并接受可选的 filter 函数来缩小条目属性。这允许你根据 idslug 或 frontmatter 值(通过 data 对象)查询集合中的某些项目。

---
import { getCollection } from 'astro:content';
// 获取 `src/content/blog/` 中的所有条目
const allBlogPosts = await getCollection('blog');
// 仅返回 frontmatter 中 `draft: true` 的条目
const draftBlogPosts = await getCollection('blog', ({ data }) => {
return data.draft === true;
});
---

有关示例请参考 内容集合指南 以获取示例用法。

添加于: astro@2.5.0

类型:

  • (collection: string, contentSlugOrDataId: string) => CollectionEntry<collection>
  • ({ collection: string, id: string }) => CollectionEntry<collection>
  • ({ collection: string, slug: string }) => CollectionEntry<collection>

getEntry() 是一个函数,可通过集合名称和条目 id (对于 type: 'data' 集合)或条目 slug (对于 type: 'content' 集合)检索单个集合条目。getEntry()也可用于获取引用条目,以访问databodyrender()属性:

---
import { getEntry } from 'astro:content';
// 得到 `src/content/blog/enterprise.md`
const enterprisePost = await getEntry('blog', 'enterprise');
// 得到 `src/content/captains/picard.yaml`
const picardProfile = await getEntry('captains', 'picard');
// 得到 the profile referenced by `data.captain`
const enterpriseCaptainProfile = await getEntry(enterprisePost.data.captain);
---

有关内容集合的示例,请参考 查询集合条目.

添加于: astro@2.5.0

类型:

  • (Array<{ collection: string, id: string }>) => Array<CollectionEntry<collection>>
  • (Array<{ collection: string, slug: string }>) => Array<CollectionEntry<collection>>

getEntries() 是一个从同一集合中检索多个集合条目的函数。这对于返回引用条目的数组访问其关联的databodyrender()属性非常有用。

---
import { getEntries } from 'astro:content';
const enterprisePost = await getEntry('blog', 'enterprise');
// 获取由 `data.relatedPosts` 引用的相关帖子
const enterpriseRelatedPosts = await getEntries(enterprisePost.data.relatedPosts);
---

类型:(collection: string, slug: string) => CollectionEntry<collection>

getEntryBySlug() 是一个函数,用于通过集合名称和条目 slug 检索单个集合条目。

---
import { getEntryBySlug } from 'astro:content';
const enterprise = await getEntryBySlug('blog', 'enterprise');
---

有关示例请参考 内容集合指南 以获取示例用法。

类型:(collection: string, id: string) => Promise<CollectionEntry<collection>>

添加于: astro@2.5.0

getDataEntryById() 是一个用于通过集合名称和条目 id 检索单个集合条目的函数。

---
import { getDataEntryById } from 'astro:content';
const picardProfile = await getDataEntryById('captains', 'picard');
---

getCollection()getEntryBySlug() 函数都会返回 CollectionEntry 类型的条目。这个类型可以从 astro:content 中获取:

import type { CollectionEntry } from 'astro:content';

CollectionEntry<TCollectionName> 类型是一个对象,具有以下值。 TCollectionName 是你正在查询的集合的名称(例如 CollectionEntry<'blog'>)。

适用于: type: 'content' and type: 'data' 集合

示例类型:

  • 内容集合: 'entry-1.md' | 'entry-2.md' | ...
  • 数据集合: 'author-1' | 'author-2' | ...

一个使用相对于 src/content/[collection] 的文件路径的唯一 ID。根据集合条目文件路径枚举所有可能的字符串值。请注意,类型: 'content' 的集合在其 ID 中包含文件扩展名,而定义为 type: 'data' 的集合则不包含。

适用于: type: 'content' and type: 'data' 集合

示例类型: 'blog' | 'authors' | ...

src/content/ 下顶级文件夹的名称,条目位于该文件夹中。该名称用于在模式和查询函数中引用集合。

适用于: type: 'content' and type: 'data' 集合

类型:CollectionSchema<TCollectionName>

一个从集合模式推断出的 frontmatter 属性对象(参考 defineCollection())。如果没有配置模式,则默认为 any

适用于: 仅仅 type: 'content' 集合

示例类型: 'entry-1' | 'entry-2' | ...

可用于 Markdown 或 MDX 文档的 URL 标头。默认为不含文件扩展名的 “id”,但可以通过在文件的 frontmatter 中设置slug属性来覆盖。

适用于:type: 'content' 集合

类型:string

一个包含 Markdown 或 MDX 文档原始未编译的 body 的字符串。

适用于:type: 'content' 集合

类型:() => Promise<RenderedEntry>

一个用于编译给定的 Markdown 或 MDX 文档以进行渲染的函数。它返回以下属性:

---
import { getEntryBySlug } from 'astro:content';
const entry = await getEntryBySlug('blog', 'entry-1');
const { Content, headings, remarkPluginFrontmatter } = await entry.render();
---

有关示例请参考 内容集合指南 以获取示例用法。

astro:content 模块也导出了以下类型,供你在 Astro 项目中使用:

添加于: astro@3.1.0

这是一个在 src/content/config.* 文件中定义的所有集合名称的字符串联合类型。当定义一个可以接受任何集合名称的通用函数时,这个类型很有用。

import type { CollectionKey, getCollection } from 'astro:content';
async function getCollection(collection: CollectionKey) {
return getCollection(collection);
}

添加于: astro@3.1.0

一个在 src/content/config.* 文件中定义的所有 type: 'content' 集合名称的字符串联合类型。

添加于: astro@3.1.0

一个在 src/content/config.* 文件中定义的所有 type: 'data' 集合名称的字符串联合类型。

defineCollectionschema 函数形状中所使用的 context 对象。当为多个集合构建可重用的模式时,这个类型很有用。

它包括了以下属性:

import type { SchemaContext } from 'astro:content';
export const imageSchema = ({ image }: SchemaContext) =>
z.object({
image: image(),
description: z.string().optional(),
});
const blog = defineCollection({
type: 'content',
schema: ({ image }) => z.object({
title: z.string(),
permalink: z.string().optional(),
image: imageSchema({ image })
}),
});

中间件(astro:middleware

段落标题 中间件(astro:middleware)

添加于: astro@2.6.0

中间件使你能拦截请求和响应,并在每次渲染页面或端点时动态注入行为。有关功能和用法示例,请参考中间件指南

类型:(context: APIContext, next: MiddlewareNext) => Promise<Response> | Response | Promise<void> | void

一个在 src/middleware.js 里的必须导出的函数,它将在每次渲染页面或端点时被调用。它接受两个参数:contextnext()onRequest() 必须返回一个 Response:要么直接返回,要么通过调用 next() 返回。

src/middleware.js
export function onRequest (context, next) {
// 拦截一个请求的响应数据
// 可选修改响应
// 直接返回一个 Response 对象,或者调用 `next()` 的结果
return next();
};

类型:APIContext

onRequest() 的第一个参数是一个上下文对象。它反映了许多 Astro 全局属性。

有关更多信息,请参阅 端点上下文

类型:(rewritePayload?: string | URL | Request) => Promise<Response>

onRequest() 的第二个参数是一个调用链中的所有后续中间件,并返回一个 Response 的函数。例如,其他中间件可以修改响应的 HTML 主体,等待 next() 的结果将允许你的中间件响应这些更改。

自从 Astro v4.13.0,next() 接受一个可选的 URL 路径参数,形式为字符串、URLRequest,用于重写当前请求而不重新触发新的渲染阶段。

类型:(...handlers: MiddlewareHandler[]) => MiddlewareHandler

一个接受中间件函数作为参数的函数,它将按照它们传递的顺序执行它们。

src/middleware.js
import { sequence } from "astro:middleware";
async function validation(_, next) {...}
async function auth(_, next) {...}
async function greeting(_, next) {...}
export const onRequest = sequence(validation, auth, greeting);

类型:(context: CreateContext) => APIContext

添加于: astro@2.8.0

一个底层 API,用于创建一个 APIContext 以传递给 Astro 中间件的 onRequest() 函数。

此函数可以由集成/适配器用于执行 Astro 中间件。

类型:(value: unknown) => string

添加于: astro@2.8.0

一个底层 API,它接受任何值并尝试返回它的序列化版本(一个字符串)。如果该值无法序列化,该函数将抛出一个运行时错误。

添加于: astro@3.5.0

此模块提供了一些函数,帮助你使用项目配置的语言环境设置创建 URL。

使用 i18n 路由为你的项目创建路由将依赖于你设置的某些配置值,这些值会影响你的页面路由。使用这些函数创建路由时,请确保考虑到你的个人设置,包括:

另外,请注意,这些函数为你的 defaultLocale 创建的返回 URL 将反映你的 i18n.routing 配置。

有关功能和使用示例,请参阅我们的 i18n 路由指南

类型:(locale: string, path?: string, options?: GetLocaleOptions) => string

getRelativeLocaleUrl(locale: string, path?: string, options?: GetLocaleOptions): string

使用此函数来检索一个语言环境的相对路径。如果该语言环境不存在,Astro 会抛出一个错误。

---
getRelativeLocaleUrl("fr");
// 返回 /fr
getRelativeLocaleUrl("fr", "");
// 返回 /fr
getRelativeLocaleUrl("fr", "getting-started");
// 返回 /fr/getting-started
getRelativeLocaleUrl("fr_CA", "getting-started", {
prependWith: "blog"
});
// 返回 /blog/fr-ca/getting-started
getRelativeLocaleUrl("fr_CA", "getting-started", {
prependWith: "blog",
normalizeLocale: false
});
// 返回 /blog/fr_CA/getting-started
---

类型:(locale: string, path: string, options?: GetLocaleOptions) => string

当 [site] 配置了值时,使用这个函数来检索一个语言环境的绝对路径。如果 [site] 没有被配置,该函数将返回一个相对 URL。如果语言环境不存在,Astro 会抛出一个错误。

src/pages/index.astro
---
// 如果 `site` 被设置为 `https://example.com`
getAbsoluteLocaleUrl("fr");
// 返回 https://example.com/fr
getAbsoluteLocaleUrl("fr", "");
// 返回 https://example.com/fr
getAbsoluteLocaleUrl("fr", "getting-started");
// 返回 https://example.com/fr/getting-started
getAbsoluteLocaleUrl("fr_CA", "getting-started", {
prependWith: "blog"
});
// 返回 https://example.com/blog/fr-ca/getting-started
getAbsoluteLocaleUrl("fr_CA", "getting-started", {
prependWith: "blog",
normalizeLocale: false
});
// 返回 https://example.com/blog/fr_CA/getting-started
---

getRelativeLocaleUrlList()

段落标题 getRelativeLocaleUrlList()

类型:(path?: string, options?: GetLocaleOptions) => string[]

像使用 getRelativeLocaleUrl 那样使用此函数,返回所有语言环境的相对路径列表。

getAbsoluteLocaleUrlList()

段落标题 getAbsoluteLocaleUrlList()

类型:(path?: string, options?: GetLocaleOptions) => string[]

像使用 getAbsoluteLocaleUrl 那样使用此函数,返回所有语言环境的绝对路径列表。

类型:(locale: string) => string

当配置了自定义语言环境路径时,此函数返回与一个或多个 codes 关联的 path

astro.config.mjs
export default defineConfig({
i18n: {
locales: ["es", "en", {
path: "french",
codes: ["fr", "fr-BR", "fr-CA"]
}]
}
})
src/pages/index.astro
---
getPathByLocale("fr"); // 返回 "french"
getPathByLocale("fr-CA"); // 返回 "french"
---

类型:(path: string) => string

此函数返回与语言环境 path 关联的 code

astro.config.mjs
export default defineConfig({
i18n: {
locales: ["es", "en", {
path: "french",
codes: ["fr", "fr-BR", "fr-CA"]
}]
}
})
src/pages/index.astro
---
getLocaleByPath("french"); // 返回 "fr",因为这是首个配置的代码
---

类型:(context: APIContext, statusCode?: ValidRedirectStatus) => Promise<Response>

添加于: astro@4.6.0

此函数返回一个 Response,将重定向到配置的 defaultLocale。它接受一个可选的有效重定向状态码。

middleware.js
import { defineMiddleware } from "astro:middleware";
import { redirectToDefaultLocale } from "astro:i18n";
export const onRequest = defineMiddleware((context, next) => {
if (context.url.pathname.startsWith("/about")) {
return next();
} else {
return redirectToDefaultLocale(context, 302);
}
})

类型:(context: APIContext, response: Response) => Promise<Response>

添加于: astro@4.6.0

此函数允许你在自己的中间件中使用你的 i18n.fallback 配置

middleware.js
import { defineMiddleware } from "astro:middleware";
import { redirectToFallback } from "astro:i18n";
export const onRequest = defineMiddleware(async (context, next) => {
const response = await next();
if (response.status >= 300) {
return redirectToFallback(context, response)
}
return response;
})

类型:(context: APIContext, response?: Response) => Promise<Response> | undefined

添加于: astro@4.6.0

当以下情况发生时,在你的路由中间件中使用此函数来返回一个 404 错误:

  • 当前路径不是根路径。例如://<base>
  • URL 中不包含语言环境代码

当传递了一个 Response,由此函数发出的新 Response 将包含原始响应的相同头信息。

middleware.js
import { defineMiddleware } from "astro:middleware";
import { notFound } from "astro:i18n";
export const onRequest = defineMiddleware((context, next) => {
const pathNotFound = notFound(context);
if (pathNotFound) {
return pathNotFound;
}
return next();
})

类型:(options: { prefixDefaultLocale: boolean, redirectToDefaultLocale: boolean }) => MiddlewareHandler

添加于: astro@4.6.0

此函数允许你以编程方式创建 Astro i18n 中间件。

当你仍然想要使用默认的 i18n 逻辑,但只在你的网站添加少数例外时,这个功能非常有用。

middleware.js
import { middleware } from "astro:i18n";
import { sequence, defineMiddleware } from "astro:middleware";
const customLogic = defineMiddleware(async (context, next) => {
const response = await next();
// 在这里解析响应后的自定义逻辑。
// 可以捕获来自 Astro i18n 中间件的响应。
return response;
});
export const onRequest = sequence(customLogic, middleware({
prefixDefaultLocale: true,
redirectToDefaultLocale: false
}))

类型:(context: APIContext) => boolean

添加于: astro@4.6.0

检查当前 URL 是否包含已配置的语言环境代码。在内部,此函数将使用 APIContext#url.pathname

middleware.js
import { defineMiddleware } from "astro:middleware";
import { requestHasLocale } from "astro:i18n";
export const onRequest = defineMiddleware(async (context, next) => {
if (requestHasLocale(context)) {
return next();
}
return new Response("Not found", { status: 404 });
})

视图过渡客户端 API (astro:transitions/client)

段落标题 视图过渡客户端 API (astro:transitions/client)

添加于: astro@3.2.0

此模块提供了一些函数,用于控制和与视图过渡 API 和客户端路由进行交互。

对于功能和使用示例,请参阅我们的视图过渡指南

类型:(href: string, options?: Options) => void

添加于: astro@3.2.0

一个使用视图过渡 API 导航到给定 href 的函数。

此函数签名基于 浏览器 Navigation API 中的 navigate 函数。虽然基于 Navigation API,但此函数是在 History API 之上实现的,以允许在不重新加载页面的情况下进行导航。

类型:'auto' | 'push' | 'replace'
默认值:'auto'

添加于: astro@3.2.0

定义了如何将此导航添加到浏览器历史记录中。

  • 'push':路由将使用 history.pushState 在浏览器历史记录中创建一个新条目。
  • 'replace':路由将使用 history.replaceState 更新 URL,而不会在导航中添加新条目。
  • 'auto'(默认):路由将尝试 history.pushState,但如果无法进行过渡,则当前 URL 将保持不变,浏览器历史记录不会发生变化。

此选项遵循浏览器 Navigation API 中的 history 选项,但简化了在 Astro 项目中可能发生的情况。

类型:FormData

添加于: astro@3.5.0

一个 FormData 对象,用于 POST 请求。

当提供此选项时,导航目标页面的请求将以 POST 请求的形式发送,内容为表单数据对象。

当提交一个带有视图过渡的 HTML 表单时,将使用此方法代替默认的页面重新加载导航。调用此方法允许以编程方式触发相同的行为。

类型:any

添加于: astro@3.6.0

与导航相关的 astro:before-preparationastro:before-swap 事件中包含的任意数据。

此选项模仿了浏览器 Navigation API 中的 info 选项

类型:any

添加于: astro@3.6.0

与导航相关的 NavitationHistoryEntry 对象中关联的任意数据。此数据可以通过 history.getState 函数 从 History API 中检索。

此选项模仿了浏览器 Navigation API 中的 state 选项

类型:Element

添加于: astro@3.6.0

此导航的触发元素,如果有的话。此元素将在以下事件中可用:

  • astro:before-preparation
  • astro:before-swap

类型:boolean

添加于: astro@3.2.0

当前浏览器是否支持并启用视图过渡。

transitionEnabledOnThisPage

段落标题 transitionEnabledOnThisPage

类型:boolean

添加于: astro@3.2.0

当前页面是否启用了视图过渡以进行客户端导航。这可以用于使组件在视图过渡页面上的行为有所不同。

类型:() => 'none' | 'animate' | 'swap'

添加于: astro@3.6.0

返回在浏览器不支持视图过渡时使用的回退策略。

有关如何选择和配置回退行为的详细信息,请参阅 回退控制 指南。

astro:before-preparation 事件

段落标题 astro:before-preparation 事件

在视图过渡中导航开始时触发的事件。此事件发生在任何请求之前,并且不会更改任何浏览器状态。

此事件具有以下属性:

有关如何使用此事件的详细信息,请参阅 视图过渡指南.

astro:after-preparation 事件

段落标题 astro:after-preparation 事件

使用视图过渡加载导航中的下一个页面后触发的事件。

此事件没有属性。

有关如何使用此事件的详细信息,请参阅 视图过渡指南.

在视图过渡中导航的下一个页面解析、准备并链接到 document 后,但在任何内容在 document 之间交换之前触发的事件。

此事件不能取消。调用 preventDefault() 是无效的。

此事件具有以下属性:

有关如何使用此事件的详细信息,请参阅 视图过渡指南.

在视图过渡中导航的下一个页面内容交换后,但在视图过渡结束之前触发的事件。

在触发此事件时,历史记录条目和滚动位置已经更新。

在页面完成加载后触发的事件,无论是通过视图过渡导航还是浏览器原生导航。

当视图过渡在页面上启用时,通常在 DOMContentLoaded 上执行的代码应更改为在此事件上执行。

添加于: astro@3.6.0

类型:URL

在导航期间定义的任意数据。

这是在 navigate() 函数info 选项 中传递的文字值。

类型:Element | undefined

触发导航的元素。例如,这可以是点击的 <a> 元素。

当使用 navigate() 函数 时,这将是调用中指定的元素。

类型:Document

导航中下一个页面的 document。此 document 的内容将替换当前 document 的内容。

类型:'push' | 'replace' | 'traverse'

正在发生的导航类型。

  • push: 正在为新页面创建一个新的 NavigationHistoryEntry
  • replace: 当前的 NavigationHistoryEntry 正在被新页面的条目替换。
  • traverse: 没有创建 NavigationHistoryEntry。历史记录中的位置正在改变。 遍历的方向由 direction 属性 给出

类型:Direction

过渡的方向。

  • forward: 在历史记录中导航到下一个页面或新页面。
  • back: 在历史记录中导航到前一个页面。
  • 其他监听器可能设置的任何其他内容。

类型:URL

正在导航的页面的 URL。

类型:URL

正在导航的页面的 URL。此属性可以修改,在生命周期结束时使用的值将是下一个页面的 NavigationHistoryEntry 的值。

类型:FormData | undefined

一个用于 POST 请求的 FormData 对象。

当此属性设置时,将使用给定的表单数据对象作为内容发送 POST 请求到 to URL,而不是正常的 GET 请求。

当提交一个带有视图过渡的 HTML 表单时,此字段会自动设置为表单中的数据。当使用 navigate() 函数 时,此值与给定的选项相同。

类型:() => Promise<void>

在导航过程中下个阶段的实现(加载下一个页面)。此实现可以覆盖以添加额外的行为。

类型:ViewTransition

在导航过程中使用的视图过渡对象。在浏览器不支持 视图过渡 API 的情况下,这是一个对象,实现了相同的 API 以方便使用,但没有 DOM 集成。

类型:() => void

document 交换逻辑的实现。

有关如何构建自定义交换函数的详细信息,请参阅 视图过渡指南.

默认情况下,此实现将按顺序调用以下函数:

类型:(newDocument: Document) => void

标记在新的 document 中不应执行的脚本。这些脚本已经在当前 document 中,并且没有使用 data-astro-rerun 标记为重新执行。

类型:(newDocument: Document) => void

在 document 根节点之间交换属性,如 lang 属性。这也包括 Astro 注入的内部属性,如 data-astro-transition,这使得过渡方向可用于 Astro 生成的 CSS 规则。

在构建自定义交换函数时,重要的是调用此函数,以避免破坏视图过渡的动画。

类型:(newDocument: Document) => void

从当前 document 的 <head> 中删除所有未持久化到新 document 的元素。然后将新 document 的 <head> 中的所有新元素附加到当前 document 的 <head>

类型:() => () => void

在当前页面上存储聚焦的元素,并返回一个函数,当调用时,如果聚焦的元素被持久化,则将焦点返回给该元素。

类型:(newBody: Element, oldBody: Element) => void

用新 document 的 body 替换旧的 body。然后,遍历旧 body 中应持久化的每个元素,并在新 body 中找到匹配的元素,将旧元素交换回原位。

添加于: astro@4.15.0

Action 帮助你构建一个类型安全的后端,你可以从客户端代码和 HTML 表单中调用它。所有用于定义和调用 Action 的工具函数都由 astro:actions 模块暴露。有关示例和使用说明,请参阅 Actions 指南

添加于: astro@4.15.0

defineAction() 函数接受一个 handler() 函数,其中包含在调用 Action 时要运行的服务器逻辑,以及一个可选的 input 属性,用于在运行时验证输入参数。

export const server = {
getGreeting: defineAction({
input: z.object({
name: z.string(),
}),
handler: async (input, context) => {
return `Hello, ${input.name}!`
}
})
}

类型:(input, context) => any

defineAction() 函数接受一个 handler() 函数,其中包含在调用 Action 时要运行的服务器逻辑。此函数可以返回数据,这些数据将自动序列化并发送给调用者。

handler() 函数被调用时,接受用户输入作为其第一个参数。如果设置了 input 验证器,那么用户输入将在传递给 handler() 前进行验证。第二个参数是一个 context 对象,包含大多数 Astro 的 标准端点上下文,不包括 getActionResult(), callAction(), 和 redirect()

返回值使用 devalue 库 进行解析。它支持 JSON 值,以及 Date(), Map(), Set(), 或 URL() 的实例。

类型:ZodObject | undefined

可选的 input 属性接受一个 Zod 验证器,用于在运行时验证处理程序的输入。如果 action 验证失败,将返回 BAD_REQUEST 错误 并跳过 handler

如果与 accept: 'form' 一起使用,则 input 必须使用 z.object() 验证器。

此对象中支持的扩展函数包括 .refine(), .transform(), 和 .pipe()。表单数据字段支持以下验证器:

  • 使用 z.number() 验证类型为 number 的输入
  • 使用 z.boolean() 验证类型为 checkbox 的输入
  • 使用 z.instanceof(File) 验证类型为 file 的输入
  • 使用 z.array(/* validator */) 验证相同 name 的多个输入
  • 使用 z.string() 验证所有其他输入

类型:(error?: unknown | ActionError) => boolean

添加于: astro@4.15.0

isInputError() 函数常用于检查 ActionError 是否是输入验证错误。当 input 验证器是 z.object() 时,输入错误包括一个 fields 对象,其中错误消息按名称分组。

更多关于使用 isInputError() 的信息,请参见 表单输入错误指南

添加于: astro@4.15.0

ActionError 构造函数常用于在 handler() 函数中抛出错误。它接受一个 code 属性,描述发生的错误(例如:"UNAUTHORIZED"),以及一个可选的 message 属性,提供进一步的细节。

添加于: astro@4.15.0

code 属性接受所有 HTTP 状态码的人类可读版本。以下是支持的 code:

  • BAD_REQUEST (400): 客户端发送了无效的输入。当 action input 验证器验证失败时会抛出此错误。
  • UNAUTHORIZED (401): 客户端缺乏有效的身份验证凭据。
  • FORBIDDEN (403): 客户端无权访问资源。
  • NOT_FOUND (404): 服务器找不到请求的资源。
  • METHOD_NOT_SUPPORTED (405): 服务器不支持请求的方法。
  • TIMEOUT (408): 服务器在处理请求时超时。
  • CONFLICT (409): 服务器无法更新资源,因为存在冲突。
  • PRECONDITION_FAILED (412): 服务器不满足请求的前提条件。
  • PAYLOAD_TOO_LARGE (413): 服务器无法处理请求,因为负载过大。
  • UNSUPPORTED_MEDIA_TYPE (415): 服务器不支持请求的媒体类型。注意:Actions 已经检查了 JSON 和表单请求的 Content-Type 标头,所以你可能不需要手动引发此代码。
  • UNPROCESSABLE_CONTENT (422): 服务器无法处理请求,因为存在语义错误。
  • TOO_MANY_REQUESTS (429): 服务器已超出指定的速率限制。
  • CLIENT_CLOSED_REQUEST (499): 客户端在服务器响应之前关闭了请求。
  • INTERNAL_SERVER_ERROR (500): 服务器意外失败。
  • NOT_IMPLEMENTED (501): 服务器不支持请求的功能。
  • BAD_GATEWAY (502): 服务器从上游服务器接收到无效响应。
  • SERVICE_UNAVAILABLE (503): 服务器暂时不可用。
  • GATEWAY_TIMEOUT (504): 服务器从上游服务器接收到超时。

添加于: astro@4.15.0

message 属性接受一个字符串。(例如:“用户必须登录。“)

Astro 包括几个内置的组件供你在你的项目中使用。在 .astro 文件中可以通过 import {} from 'astro:components'; 引用所有的内置组件。

你可以使用 ComponentProp 类型 工具函数来引用这些组件的 Props

---
import { Code } from 'astro:components';
---
<!-- 使用语法凸显部分 JavaScript 代码-->
<Code code={`const foo = 'bar';`} lang="js" />
<!-- 可选:定制你的主题 -->
<Code code={`const foo = 'bar';`} lang="js" theme="dark-plus" />
<!-- 可选:启用文字包装 -->
<Code code={`const foo = 'bar';`} lang="js" wrap />
<!-- 可选:输出内联代码 -->
<p>
<Code code={`const foo = 'bar';`} lang="js" inline />
will be rendered inline.
</p>
<!-- 可选: defaultColor -->
<Code code={`const foo = 'bar';`} lang="js" defaultColor={false} />

该组件在构建时为代码块提供语法高亮(不包括客户端 JavaScript)。该组件由 Shiki 内部驱动,它支持所有流行的 主题语言。另外,你可以通过将自定义主题、语言、转换器默认配色 分别传递给 themelangtransformersdefaultColor 属性以添加它们。

添加于: astro@4.11.0

Shiki 转换器 可以通过将其作为数组传递到 transformers 属性中,来选择性地应用于代码。从 Astro v4.14.0 开始,你还可以为 Shiki 的 meta 属性 提供一个字符串,以将选项传递给转换器。

注意,transformers 只能用于类,同时你必须提供自己的 CSS 规则来针对代码块的元素。

src/pages/index.astro
---
import { transformerNotationFocus, transformerMetaHighlight } from '@shikijs/transformers'
import { Code } from 'astro:components'
const code = `const foo = 'hello'
const bar = ' world'
console.log(foo + bar) // [!code focus]
`
---
<Code
code={code}
lang="js"
transformers={[transformerMetaHighlight()]}
meta="{1,3}" />
<style is:global>
pre.has-focused .line:not(.focused) {
filter: blur(1px);
}
</style>

一个与 set:* 指令 一起使用的组件,用于渲染 HTML 内容而不添加任何额外的包裹元素。

src/components/SetHtml.astro
---
const htmlString = '<p>Raw HTML content</p>';
---
<Fragment set:html={htmlString} />

请参见在 Astro 语法中使用片段的更多信息。

要安装 Prism 高亮器组件,需要先安装 @astrojs/prism 包:

Terminal window
npm i @astrojs/prism
---
import { Prism } from '@astrojs/prism';
---
<Prism lang="js" code={`const foo = 'bar';`} />

这个组件通过应用 Prism 的 CSS 类为代码块提供特定语言的语法高亮。注意,你需要提供 Prism 的 CSS 样式表(或用自己的),以启用语法高亮!参见 Prism 配置部分了解更多细节。

参见 Prism 支持的语言列表,在那里你可以找到一种语言的对应别名。而且,你也可以用 lang="astro" 来展示 Astro 代码块!

src/components/MyComponent.astro
---
// 导入图像组件和图片
import { Image } from 'astro:assets';
import myImage from "../assets/my_image.png"; // Image is 1600x900
---
<!-- `alt` 在 Image 组件中是必需的属性 -->
<Image src={myImage} alt="A description of my image." />
<!-- 输出 -->
<!-- Image 组件已经过优化,并且对应的属性也被强制使用。 -->
<img
src="/_astro/my_image.hash.webp"
width="1600"
height="900"
decoding="async"
loading="lazy"
alt="A description of my image."
/>
  • src(必需的)
  • alt(必需的)
  • width 和 height(对 public/ 和远程图像而言是必需的)
  • format
  • quality
  • densities
  • widths

除了上述属性之外,<Image /> 组件还接受 HTML <img> 标签接受的所有属性。

详见图像指南

添加于: astro@3.3.0

使用内置的 <Picture /> Astro 组件来展示具有多种格式和(或)尺寸的响应式图像。

src/pages/index.astro
---
import { Picture } from 'astro:assets';
import myImage from "../assets/my_image.png"; // 图像的分辨率为 1600x900
---
<!-- 在图片组件上 `alt` 属性是必需的 -->
<Picture src={myImage} formats={['avif', 'webp']} alt="A description of my image." />
<!-- 输出 -->
<picture>
<source srcset="/_astro/my_image.hash.avif" type="image/avif" />
<source srcset="/_astro/my_image.hash.webp" type="image/webp" />
<img
src="/_astro/my_image.hash.png"
width="1600"
height="900"
decoding="async"
loading="lazy"
alt="A description of my image."
/>
</picture>

详见图像指南

<Picture /> 接受 <Image /> 组件的所有属性,以及以下属性:

一个图像格式的数组,用于 <source> 标签。默认情况下,它被设置为 ['webp']

用于作为 <img> 标签的回退值的格式。对于静态图像,默认为 .png;对于动画图像,默认为 .gif;对于 SVG 文件,默认为 .svg

一个被添加到 <picture> 标签的属性对象。使用该属性可将属性应用于外部的 <picture> 元素本身。除了用于图像转换的属性外,直接应用于 <Picture /> 组件的属性将应用于内部的 <img> 元素。

一个通用组件,用于呈现 内容集合条目 的内容。

首先,使用 getCollection()getEntry() 查询一个或多个条目。然后,entry.render() 函数可以返回 <Content /> 组件,以供在 .astro 文件模板中使用。

src/pages/render-example.astro
---
import { getEntry } from 'astro:content';
const entry = await getEntry('blog', 'post-1');
const { Content } = await entry.render();
---
<p>Published on: {entry.data.published.toDateString()}</p>
<Content />

添加于: astro@2.9.0

在每个希望应用视图过渡动画的页面上,通过导入并将 <ViewTransitions /> 路由组件添加到 <head> 中,来选择使用单个页面上的视图过渡动画。

src/pages/index.astro
---
import { ViewTransitions } from 'astro:transitions';
---
<html lang="en">
<head>
<title>My Homepage</title>
<ViewTransitions />
</head>
<body>
<h1>Welcome to my website!</h1>
</body>
</html>

查看更多关于如何控制路由器和向页面元素和组件添加过渡动画指令的信息。

---
import { Debug } from 'astro:components';
const serverObject = {
a: 0,
b: "string",
c: {
nested: "object"
}
}
---
<Debug {serverObject} />

这个组件提供了无需 JavaScript 在客户端检查数值的方法。

贡献

你有什么想法?

社区
京ICP备15031610号-99