Skip to content

API 参考

¥Astro global

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

¥The Astro global is available in all contexts in .astro files. It has the following functions:

Astro.glob() 是一种将许多本地文件加载到静态站点设置中的方法。

¥Astro.glob() is a way to load many local files into your static site setup.

src/components/my-component.astro
---
const posts = await Astro.glob('../pages/post/*.md'); // returns an array of posts that live at ./src/pages/post/*.md
---
<div>
{posts.slice(0, 3).map((post) => (
<article>
<h2>{post.frontmatter.title}</h2>
<p>{post.frontmatter.description}</p>
<a href={post.url}>Read more</a>
</article>
))}
</div>

.glob() 仅采用一个参数:你要导入的本地文件的相对 URL 全局。它是异步的,并返回匹配文件的导出数组。

¥.glob() only takes one parameter: a relative URL glob of which local files you’d like to import. It’s asynchronous, and returns an array of the exports from matching files.

.glob() 不能接受变量或插入它们的字符串,因为它们不可静态分析。(请参阅 the troubleshooting guide for a workaround.) This is because Astro.glob() is a wrapper of Vite’s import.meta.glob()

¥.glob() can’t take variables or strings that interpolate them, as they aren’t statically analyzable. (See the troubleshooting guide for a workaround.) This is because Astro.glob() is a wrapper of Vite’s import.meta.glob().

¥Markdown Files

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

¥Markdown files loaded with Astro.glob() return the following MarkdownInstance interface:

export interface MarkdownInstance<T extends Record<string, any>> {
/* Any data specified in this file's YAML frontmatter */
frontmatter: T;
/* The absolute file path of this file */
file: string;
/* The rendered path of this file */
url: string | undefined;
/* Astro Component that renders the contents of this file */
Content: AstroComponentFactory;
/** (Markdown only) Raw Markdown file content, excluding layout HTML and YAML frontmatter */
rawContent(): string;
/** (Markdown only) Markdown file compiled to HTML, excluding layout HTML */
compiledContent(): string;
/* Function that returns an array of the h1...h6 elements in this file */
getHeadings(): Promise<{ depth: number; slug: string; text: string }[]>;
default: AstroComponentFactory;
}

你可以选择使用 TypeScript 泛型为 frontmatter 变量提供类型。

¥You can optionally provide a type for the frontmatter variable using a TypeScript generic.

---
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 Files

Astro 文件具有以下接口:

¥Astro files have the following interface:

export interface AstroInstance {
/* The file path of this file */
file: string;
/* The URL for this file (if it is in the pages directory) */
url: string | undefined;
default: AstroComponentFactory;
}

¥Other Files

其他文件可能有各种不同的接口,但如果你确切知道无法识别的文件类型包含什么内容,Astro.glob() 就会接受 TypeScript 泛型。

¥Other files may have various different interfaces, but Astro.glob() accepts a TypeScript generic if you know exactly what an unrecognized file type contains.

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

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

¥Astro.props is an object containing any values that have been passed as component attributes. Layout components for .md and .mdx files receive frontmatter values as props.

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="My First Post" date="09 Aug 2022" />
Learn more about how Markdown and MDX Layouts handle props.

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

¥Astro.params is an object containing the values of dynamic route segments matched for this request.

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

¥In static builds, this will be the params returned by getStaticPaths() used for prerendering dynamic routes.

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

¥In SSR builds, this can be any value matching the path segments in the dynamic route pattern.

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

¥See also: params

类型:Request

¥Type: Request

Astro.request 是标准 要求 对象。它可用于获取 urlheadersmethod,甚至请求的正文。

¥Astro.request is a standard Request object. It can be used to get the url, headers, method, and even body of the request.

<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

¥See also: Astro.url

类型:ResponseInit & { readonly headers: Headers }

¥Type: ResponseInit & { readonly headers: Headers }

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

¥Astro.response is a standard ResponseInit object. It has the following structure.

  • status:响应的数字状态代码,例如 200

  • statusText:与状态代码关联的状态消息,例如 'OK'

  • headers:可用于设置响应的 HTTP 标头的 Headers 实例。

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

¥Astro.response is used to set the status, statusText, and headers for a page’s response.

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

或者设置标题:

¥Or to set a header:

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

类型:AstroCookies

¥Type: AstroCookies

Added in: astro@1.4.0

Astro.cookies 包含用于在 服务器端渲染 模式下读取和操作 cookie 的实用程序。

¥Astro.cookies contains utilities for reading and manipulating cookies in server-side rendering mode.

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

¥Type: (key: string, options?: AstroCookieGetOptions) => AstroCookie | undefined

获取 cookie 作为 AstroCookie 对象,其中包含 value 和用于将 cookie 转换为非字符串类型的实用函数。

¥Gets the cookie as an AstroCookie object, which contains the value and utility functions for converting the cookie to non-string types.

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

¥Type: (key: string, options?: AstroCookieGetOptions) => boolean

该 cookie 是否存在。如果 cookie 已通过 Astro.cookies.set() 设置,则返回 true,否则将检查 Astro.request 中的 cookie。

¥Whether this cookie exists. If the cookie has been set via Astro.cookies.set() this will return true, otherwise it will check cookies in the Astro.request.

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

¥Type: (key: string, value: string | object, options?: AstroCookieSetOptions) => void

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

¥Sets the cookie key to the given value. This will attempt to convert the cookie value to a string. Options provide ways to set cookie features, such as the maxAge or httpOnly.

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

¥Type: (key: string, options?: AstroCookieDeleteOptions) => void

通过将到期日期设置为过去(Unix 时间为 0)来使 cookie 无效。

¥Invalidates a cookie by setting the expiration date in the past (0 in Unix time).

一旦 cookie 为 “deleted”(已过期),Astro.cookies.has() 将返回 false,而 Astro.cookies.get() 将返回 AstroCookievalueundefined。删除 cookie 时可用的选项是:domainpathhttpOnlysameSitesecure

¥Once a cookie is “deleted” (expired), Astro.cookies.has() will return false and Astro.cookies.get() will return an AstroCookie with a value of undefined. Options available when deleting a cookie are: domain, path, httpOnly, sameSite, and secure.

类型:(cookies: AstroCookies) => void

¥Type: (cookies: AstroCookies) => void

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

¥Merges a new AstroCookies instance into the current instance. Any new cookies will be added to the current instance and any cookies with the same name will overwrite existing values.

类型:() => Iterator<string>

¥Type: () => Iterator<string>

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

¥Gets the header values for Set-Cookie that will be sent out with the response.

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

¥Getting a cookie via Astro.cookies.get() returns a AstroCookie type. It has the following structure.

类型:string

¥Type: string

cookie 的原始字符串值。

¥The raw string value of the cookie.

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

¥Type: () => Record<string, any>

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

¥Parses the cookie value via JSON.parse(), returning an object. Throws if the cookie value is not valid JSON.

类型:() => number

¥Type: () => number

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

¥Parses the cookie value as a Number. Returns NaN if not a valid number.

类型:() => boolean

¥Type: () => boolean

将 cookie 值转换为布尔值。

¥Converts the cookie value to a boolean.

Added in: astro@4.1.0

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

¥Getting a cookie also allows specifying options via the AstroCookieGetOptions interface:

类型:(value: string) => string

¥Type: (value: string) => string

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

¥Allows customization of how a cookie is deserialized into a value.

Added in: astro@4.1.0

通过 Astro.cookies.set() 设置 cookie 允许传入 AstroCookieSetOptions 以自定义 cookie 的序列化方式。

¥Setting a cookie via Astro.cookies.set() allows passing in a AstroCookieSetOptions to customize how the cookie is serialized.

类型:string

¥Type: string

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

¥Specifies the domain. If no domain is set, most clients will interpret to apply to the current domain.

类型:Date

¥Type: Date

指定 cookie 过期的日期。

¥Specifies the date on which the cookie will expire.

类型:boolean

¥Type: boolean

如果为 true,则 cookie 将无法在客户端访问。

¥If true, the cookie will not be accessible client-side.

类型:number

¥Type: number

指定 cookie 有效的数字(以秒为单位)。

¥Specifies a number, in seconds, for which the cookie is valid.

类型:string

¥Type: string

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

¥Specifies a subpath of the domain in which the cookie is applied.

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

¥Type: boolean | 'lax' | 'none' | 'strict'

指定 SameSite cookie 标头的值。

¥Specifies the value of the SameSite cookie header.

类型:boolean

¥Type: boolean

如果为 true,则 cookie 仅在 https 站点上设置。

¥If true, the cookie is only set on https sites.

类型:(value: string) => string

¥Type: (value: string) => string

允许自定义如何序列化 cookie。

¥Allows customizing how the cookie is serialized.

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

¥Type: (path: string, status?: number) => Response

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

¥Allows you to redirect to another page, and optionally provide an HTTP response status code as a second parameter.

页面(而不是子组件)必须 returnAstro.redirect() 的结果才能发生重定向。

¥A page (and not a child component) must return the result of Astro.redirect() for the redirect to occur.

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

¥For statically-generated sites, this will produce a client redirect using a <meta http-equiv="refresh"> tag and does not support status codes.

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

¥When using an on-demand rendering mode, status codes are supported. Astro will serve redirected requests with a default HTTP response status of 302 unless another code is specified.

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

¥The following example redirects a user to a login page:

src/pages/account.astro
---
import { isLoggedIn } from '../utils';
const cookie = Astro.request.headers.get('cookie');
// If the user is not logged in, redirect them to the login page
if (!isLoggedIn(cookie)) {
return Astro.redirect('/login');
}
---

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

¥Type: (rewritePayload: string | URL | Request) => Promise<Response>

Added in: astro@4.13.0

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

¥Allows you to serve content from a different URL or path without redirecting the browser to a new page.

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

¥The method accepts either a string, a URL, or a Request for the location of the path.

使用字符串提供显式路径:

¥Use a string to provide an explicit path:

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

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

¥Use a URL type when you need to construct the URL path for the rewrite. The following example renders a page’s parent path by creating a new URL from the relative "../" path:

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

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

¥Use a Request type for complete control of the Request sent to the server for the new path. The following example sends a request to render the parent page while also providing headers:

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

类型:URL

¥Type: URL

Added in: astro@1.0.0-rc

从当前 Astro.request.url URL 字符串值构造的 URL 对象。对于与请求 URL 的各个属性(例如路径名和来源)进行交互非常有用。

¥A URL object constructed from the current Astro.request.url URL string value. Useful for interacting with individual properties of the request URL, like pathname and origin.

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

¥Equivalent to doing new URL(Astro.request.url).

如果未为静态站点配置 site,则 Astro.url 将处于开发模式,并且对于使用 serverhybrid 输出的按需渲染站点也是如此。

¥Astro.url will be localhost in dev mode if site is not configured for static sites, and for on-demand rendered sites using server or hybrid output.

<h1>The current URL is: {Astro.url}</h1>
<h1>The current URL pathname is: {Astro.url.pathname}</h1>
<h1>The current URL origin is: {Astro.url.origin}</h1>

你还可以使用 Astro.url 通过将其作为参数传递给 new URL() 来创建新的 URL。

¥You can also use Astro.url to create new URLs by passing it as an argument to new URL().

src/pages/index.astro
---
// Example: Construct a canonical URL using your production domain
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
// Example: Construct a URL for SEO meta tags using your current domain
const socialImageURL = new URL('/images/preview.png', Astro.url);
---
<link rel="canonical" href={canonicalURL} />
<meta property="og:image" content={socialImageURL} />

类型:string

¥Type: string

Added in: astro@1.0.0-rc

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

¥Specifies the IP address of the request. This property is only available when building for SSR (server-side rendering) and should not be used for static sites.

---
const ip = Astro.clientAddress;
---
<div>Your IP address is: <span class="address">{ ip }</span></div>

类型:URL | undefined

¥Type: URL | undefined

Astro.site 返回由 Astro 配置中的 site 组成的 URL。如果 Astro 配置中的 site 未定义,则 Astro.site 将不会被定义。

¥Astro.site returns a URL made from site in your Astro config. If site in your Astro config isn’t defined, Astro.site won’t be defined.

类型:string

¥Type: string

Added in: astro@1.0.0

Astro.generator 是在当前版本的 Astro 中添加 <meta name="generator"> 标签的便捷方法。它遵循格式 "Astro v1.x.x"

¥Astro.generator is a convenient way to add a <meta name="generator"> tag with your current version of Astro. It follows the format "Astro v1.x.x".

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

Astro.slots 包含用于修改 Astro 组件的带槽子组件的实用函数。

¥Astro.slots contains utility functions for modifying an Astro component’s slotted children.

类型:(slotName: string) => boolean

¥Type: (slotName: string) => boolean

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

¥You can check whether content for a specific slot name exists with Astro.slots.has(). This can be useful when you want to wrap slot contents, but only want to render the wrapper elements when the slot is being used.

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

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

¥Type: (slotName: string, args?: any[]) => Promise<string>

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

¥You can asynchronously render the contents of a slot to a string of HTML using Astro.slots.render().

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

Astro.slots.render() 可选择接受第二个参数:将转发给任何子函数的参数数组。这对于自定义实用程序组件非常有用。

¥Astro.slots.render() optionally accepts a second argument: an array of parameters that will be forwarded to any function children. This can be useful for custom utility components.

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

¥For example, this <Shout /> component converts its message prop to uppercase and passes it to the default slot:

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 参数:

¥A callback function passed as <Shout />’s child will receive the all-caps message parameter:

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

回调函数可以传递给带有 slot 属性的封装 HTML 元素标记内的命名插槽。此元素仅用于将回调传输到命名插槽,不会渲染到页面上。

¥Callback functions can be passed to named slots inside a wrapping HTML element tag with a slot attribute. This element is only used to transfer the callback to a named slot and will not be rendered onto the page.

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

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

¥Use a standard HTML element for the wrapping tag, or any lower case tag (e.g. <fragment> instead of <Fragment />) that will not be interpreted as a component. Do not use the HTML <slot> element as this will be interpreted as an Astro slot.

Astro.self 允许递归调用 Astro 组件。此行为允许你通过在组件模板中使用 <Astro.self> 从其内部渲染 Astro 组件。这对于迭代大型数据存储和嵌套数据结构很有帮助。

¥Astro.self allows Astro components to be recursively called. This behaviour lets you render an Astro component from within itself by using <Astro.self> in the component template. This can be helpful for iterating over large data stores and nested data-structures.

NestedList.astro
---
const { items } = Astro.props;
---
<ul class="nested-list">
{items.map((item) => (
<li>
<!-- If there is a nested data-structure we render `<Astro.self>` -->
<!-- and can pass props through with the recursive call -->
{Array.isArray(item) ? (
<Astro.self items={item} />
) : (
item
)}
</li>
))}
</ul>

然后可以像这样使用该组件:

¥This component could then be used like this:

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

并且会像这样渲染 HTML:

¥And would render HTML like this:

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

Added in: astro@2.4.0

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

¥Astro.locals is an object containing any values from the context.locals object from a middleware. Use this to access data returned by middleware in your .astro files.

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>{/* do something with each order */}</li>
})}
</ul>

类型:string | undefined

¥Type: string | undefined

Added in: astro@3.5.0

Astro.preferredLocale 是一个计算值,表示用户的首选区域设置。

¥Astro.preferredLocale is a computed value that represents the preferred locale of the user.

它是通过检查 i18n.locales 数组中配置的区域设置以及用户浏览器通过标头 Accept-Language 支持的区域设置来计算的。如果不存在此类匹配,则该值为 undefined

¥It is computed by checking the configured locales in your i18n.locales array and locales supported by the users’s browser via the header Accept-Language. This value is undefined if no such match exists.

此属性仅在构建 SSR(服务器端渲染)时可用,并且不应用于静态站点。

¥This property is only available when building for SSR (server-side rendering) and should not be used for static sites.

类型:string[] | undefined

¥Type: string[] | undefined

Added in: astro@3.5.0

Astro.preferredLocaleList 代表浏览器请求且你的网站支持的所有区域设置的数组。这会生成你的网站和访问者之间所有兼容语言的列表。

¥Astro.preferredLocaleList represents the array of all locales that are both requested by the browser and supported by your website. This produces a list of all compatible languages between your site and your visitor.

如果在你的区域设置数组中找不到浏览器请求的语言,则该值为 []:你不支持访问者的任何首选区域设置。

¥If none of the browser’s requested languages are found in your locales array, then the value is []: you do not support any of your visitor’s preferred locales.

如果浏览器没有指定任何首选语言,则该值将为 i18n.locales:你支持的所有区域设置都将被无偏好的访问者视为同等偏好。

¥If the browser does not specify any preferred languages, then this value will be i18n.locales: all of your supported locales will be considered equally preferred by a visitor with no preferences.

此属性仅在构建 SSR(服务器端渲染)时可用,并且不应用于静态站点。

¥This property is only available when building for SSR (server-side rendering) and should not be used for static sites.

类型:string | undefined

¥Type: string | undefined

Added in: astro@3.5.6

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

¥The locale computed from the current URL, using the syntax specified in your locales configuration. If the URL does not contain a /[locale]/ prefix, then the value will default to i18n.defaultLocale.

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

¥Type: (action: TAction) => ActionReturnType<TAction> | undefined

Added in: astro@4.15.0

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

¥Astro.getActionResult() is a function that returns the result of an Action submission. This accepts an action function as an argument (e.g. actions.logout) and returns a data or error object when a submission is received. Otherwise, it will return undefined.

src/pages/index.astro
---
import { actions } from 'astro:actions';
const result = Astro.getActionResult(actions.logout);
---
<form action={actions.logout}>
<button type="submit">Log out</button>
</form>
{result?.error && <p>Failed to log out. Please try again.</p>}

Added in: astro@4.15.0

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

¥Astro.callAction() is a function used to call an Action handler directly from your Astro component. This function accepts an Action function as the first argument (e.g. actions.logout) and any input that action receives as the second argument. It returns the result of the action as a promise.

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

¥Endpoint Context

端点功能 接收上下文对象作为第一个参数。它反映了 Astro 的许多全局属性。

¥Endpoint functions receive a context object as the first parameter. It mirrors many of the Astro global properties.

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

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

¥context.params is an object containing the values of dynamic route segments matched for this request.

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

¥In static builds, this will be the params returned by getStaticPaths() used for prerendering dynamic routes.

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

¥In SSR builds, this can be any value matching the path segments in the dynamic route pattern.

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

¥See also: params

Added in: astro@1.5.0

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

¥context.props is an object containing any props passed from getStaticPaths(). Because getStaticPaths() is not used when building for SSR (server-side rendering), context.props is only available in static builds.

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 传递数据

¥See also: Data Passing with props

类型:Request

¥Type: Request

标准 要求 对象。它可用于获取 urlheadersmethod,甚至请求的正文。

¥A standard Request object. It can be used to get the url, headers, method, and even body of the request.

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

也可以看看:Astro.request

¥See also: Astro.request

类型:AstroCookies

¥Type: AstroCookies

context.cookies 包含用于读取和操作 cookie 的实用程序。

¥context.cookies contains utilities for reading and manipulating cookies.

也可以看看:Astro.cookies

¥See also: Astro.cookies

类型:URL

¥Type: URL

Added in: astro@1.5.0

从当前 context.request.url URL 字符串值构造的 URL 对象。

¥A URL object constructed from the current context.request.url URL string value.

也可以看看:Astro.url

¥See also: Astro.url

类型:string

¥Type: string

Added in: astro@1.5.0

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

¥Specifies the IP address of the request. This property is only available when building for SSR (server-side rendering) and should not be used for static sites.

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

也可以看看:Astro.clientAddress

¥See also: Astro.clientAddress

类型:URL | undefined

¥Type: URL | undefined

Added in: astro@1.5.0

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

¥context.site returns a URL made from site in your Astro config. If undefined, this will return a URL generated from localhost.

也可以看看:Astro.site

¥See also: Astro.site

类型:string

¥Type: string

Added in: astro@1.5.0

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

¥context.generator is a convenient way to indicate the version of Astro your project is running. It follows the format "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

¥See also: Astro.generator

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

¥Type: (path: string, status?: number) => Response

Added in: astro@1.5.0

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

¥context.redirect() returns a Response object that allows you to redirect to another page. This function is only available when building for SSR (server-side rendering) and should not be used for static sites.

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

也可以看看:Astro.redirect()

¥See also: Astro.redirect()

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

¥Type: (rewritePayload: string | URL | Request) => Promise<Response>

Added in: astro@4.13.0

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

¥Allows you to serve content from a different URL or path without redirecting the browser to a new page.

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

¥The method accepts either a string, a URL, or a Request for the location of the path.

使用字符串提供显式路径:

¥Use a string to provide an explicit path:

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

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

¥Use a URL type when you need to construct the URL path for the rewrite. The following example renders a page’s parent path by creating a new URL from the relative "../" path:

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

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

¥Use a Request type for complete control of the Request sent to the server for the new path. The following example sends a request to render the parent page while also providing headers:

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()

¥See also: Astro.rewrite()

Added in: astro@2.4.0

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

¥context.locals is an object used to store and access arbitrary information during the lifecycle of a request.

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

¥Middleware functions can read and write the values of 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 读取信息:

¥API endpoints can only read information from context.locals:

src/pages/hello.ts
import type { APIContext } from 'astro';
export function GET({ locals }: APIContext) {
return new Response(locals.title); // "Default Title"
}

也可以看看:Astro.locals

¥See also: Astro.locals

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

¥Type: (action: TAction) => ActionReturnType<TAction> | undefined

Added in: astro@4.15.0

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

¥context.getActionResult() is a function that returns the result of an Action submission. This accepts an action function as an argument (e.g. actions.logout), and returns a data or error object when a submission is received. Otherwise, it will return undefined.

另请参阅 Astro.getActionResult()

¥See also Astro.getActionResult()

Added in: astro@4.15.0

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

¥context.callAction() is a function used to call an Action handler directly from your Astro component. This function accepts an Action function as the first argument (e.g. actions.logout) and any input that action receives as the second argument. It returns the result of the action as a promise.

另请参阅 Astro.callAction()

¥See also Astro.callAction()

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

¥Type: (options: GetStaticPathsOptions) => Promise<GetStaticPathsResult> | GetStaticPathsResult

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

¥If a page uses dynamic params in the filename, that component will need to export a getStaticPaths() function.

这个函数是必需的,因为 Astro 是一个静态站点构建器。这意味着你的整个网站是提前构建的。如果 Astro 不知道在构建时生成页面,你的用户在访问你的网站时将看不到它。

¥This function is required because Astro is a static site builder. That means that your entire site is built ahead of time. If Astro doesn’t know to generate a page at build time, your users won’t see it when they visit your site.

---
export async function getStaticPaths() {
return [
{ params: { /* required */ }, props: { /* optional */ } },
{ params: { ... } },
{ params: { ... } },
// ...
];
}
---
<!-- Your HTML template here. -->

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

¥The getStaticPaths() function should return an array of objects to determine which paths will be pre-rendered by Astro.

它还可以用于 动态路由 的静态文件端点。

¥It can also be used in static file endpoints for dynamic routing.

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

¥The params key of every returned object tells Astro what routes to build. The returned params must map back to the dynamic parameters and rest parameters defined in your component filepath.

params 被编码到 URL 中,因此仅支持字符串作为值。每个 params 对象的值必须与页面名称中使用的参数匹配。

¥params are encoded into the URL, so only strings are supported as values. The value for each params object must match the parameters used in the page name.

例如,假设你有一个位于 src/pages/posts/[id].astro 的页面。如果你从此页面导出 getStaticPaths 并返回以下路径:

¥For example, suppose that you have a page at src/pages/posts/[id].astro. If you export getStaticPaths from this page and return the following for paths:

---
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

¥Then Astro will statically generate posts/1, posts/2, and posts/3 at build time.

¥Data Passing with props

要将附加数据传递到每个生成的页面,你还可以在每个返回的路径对象上设置 props 值。与 params 不同,props 不会编码到 URL 中,因此不仅限于字符串。

¥To pass additional data to each generated page, you can also set a props value on every returned path object. Unlike params, props are not encoded into the URL and so aren’t limited to only strings.

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

¥For example, suppose that you generate pages based off of data fetched from a remote API. You can pass the full data object to the page component inside of 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>

你还可以传递常规数组,这在生成或存根已知路由列表时可能会有所帮助。

¥You can also pass a regular array, which may be helpful when generating or stubbing a known list of routes.

---
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 引用此数据:

¥Then Astro will statically generate posts/1 and posts/2 at build time using the page component in pages/posts/[id].astro. The page can reference this data using Astro.props:

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

¥Pagination is a common use-case for websites that Astro natively supports via the paginate() function. paginate() will automatically generate the array to return from getStaticPaths() that creates one URL for every page of the paginated collection. The page number will be passed as a param, and the page data will be passed as a page prop.

export async function getStaticPaths({ paginate }) {
// Load your data with fetch(), Astro.glob(), etc.
const response = await fetch(`https://pokeapi.co/api/v2/pokemon?limit=150`);
const result = await response.json();
const allPokemon = result.results;
// Return a paginated collection of paths for all posts
return paginate(allPokemon, { pageSize: 10 });
}
// If set up correctly, The page prop now has everything that
// you need to render a single page (see next section).
const { page } = Astro.props;

paginate() 有以下参数:

¥paginate() has the following arguments:

  • data - 包含传递给 paginate() 函数的页面数据的数组

  • options - 具有以下属性的可选对象:

    • pageSize - 每页显示的项目数(默认为 10

    • params - 发送用于创建动态路由的附加参数

    • props - 发送额外的属性以在每个页面上可用

paginate() 假定文件名为 [page].astro[...page].astropage 参数成为 URL 中的页码:

¥paginate() assumes a file name of [page].astro or [...page].astro. The page param becomes the page number in your URL:

  • /posts/[page].astro 将生成 URL /posts/1/posts/2/posts/3 等。

  • /posts/[...page].astro 将生成 URL /posts/posts/2/posts/3 等。

¥The pagination page prop

类型:Page<TData>

¥Type: Page<TData>

分页会将 page 属性传递给每个渲染的页面,该页面表示分页集合中的单页数据。这包括你已分页的数据 (page.data) 以及页面的元数据(page.urlpage.startpage.endpage.total 等)。此元数据对于 “下一页” 按钮或 “显示第 1-10 条,共 100 条” 消息等内容很有用。

¥Pagination will pass a page prop to every rendered page that represents a single page of data in the paginated collection. This includes the data that you’ve paginated (page.data) as well as metadata for the page (page.url, page.start, page.end, page.total, etc). This metadata is useful for things like a “Next Page” button or a “Showing 1-10 of 100” message.

类型:Array<TData>

¥Type: Array<TData>

当前页面的 paginate() 函数返回的数据数组。

¥Array of data returned from the paginate() function for the current page.

类型:number

¥Type: number

当前页面上第一个项目的索引,从 0 开始。(例如,如果是 pageSize: 25,则第 1 页上的 0、第 2 页上的 25 等)

¥Index of first item on current page, starting at 0. (e.g. if pageSize: 25, this would be 0 on page 1, 25 on page 2, etc.)

类型:number

¥Type: number

当前页面上最后一项的索引。

¥Index of last item on current page.

类型:number
默认:10

¥Type: number
Default: 10

每页有多少项。

¥How many items per-page.

类型:number

¥Type: number

所有页面的项目总数。

¥The total number of items across all pages.

类型:number

¥Type: number

当前页码,从 1 开始。

¥The current page number, starting with 1.

类型:number

¥Type: number

总页数。

¥The total number of pages.

类型:string

¥Type: string

获取当前页面的 URL(对规范 URL 有用)。

¥Get the URL of the current page (useful for canonical URLs).

类型:string | undefined

¥Type: string | undefined

获取上一页的 URL(如果在第 1 页,则为 undefined)。如果为 base 设置了值,请将基本路径添加到 URL 的前面。

¥Get the URL of the previous page (will be undefined if on page 1). If a value is set for base, prepend the base path to the URL.

类型:string | undefined

¥Type: string | undefined

获取下一页的 URL(如果没有更多页面,则为 undefined)。如果为 base 设置了值,请将基本路径添加到 URL 的前面。

¥Get the URL of the next page (will be undefined if no more pages). If a value is set for base, prepend the base path to the URL.

类型:string | undefined

¥Type: string | undefined

Added in: astro@4.12.0

获取第一页的 URL(如果在第 1 页,则为 undefined)。如果为 base 设置了值,请将基本路径添加到 URL 的前面。

¥Get the URL of the first page (will be undefined if on page 1). If a value is set for base, prepend the base path to the URL.

类型:string | undefined

¥Type: string | undefined

Added in: astro@4.12.0

获取最后一页的 URL(如果没有更多页面,则为 undefined)。如果为 base 设置了值,请将基本路径添加到 URL 的前面。

¥Get the URL of the last page (will be undefined if no more pages). If a value is set for base, prepend the base path to the URL.

所有 ESM 模块都包含 import.meta 属性。Astro 添加了 import.meta.envVite

¥All ESM modules include a import.meta property. Astro adds import.meta.env through Vite.

import.meta.env.SSR 可以用来知道什么时候在服务器上渲染。有时你可能需要不同的逻辑,例如仅应在客户端中渲染的组件:

¥**import.meta.env.SSR** can be used to know when rendering on the server. Sometimes you might want different logic, like a component that should only be rendered in the client:

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

¥Images (astro:assets)

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

¥Type: (options: UnresolvedImageTransform) => Promise<GetImageResult>

getImage() 函数旨在生成要在其他地方使用的图片,而不是直接在 HTML 中使用,例如在 API 路由 中。它还允许你创建自己的自定义 <Image /> 组件。

¥The getImage() function is intended for generating images destined to be used somewhere else than directly in HTML, for example in an API Route. It also allows you to create your own custom <Image /> component.

getImage() 使用 与 Image 组件具有相同的属性 的选项对象(alt 除外)。

¥getImage() takes an options object with the same properties as the Image component (except 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>

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

¥It returns an object with the following type:

type GetImageResult = {
/* Additional HTML attributes needed to render the image (width, height, style, etc..) */
attributes: Record<string, any>;
/* Validated parameters passed */
options: ImageTransform;
/* Original parameters passed */
rawOptions: ImageTransform;
/* Path to the generated image */
src: string;
srcSet: {
/* Generated values for srcset, every entry has a url and a size descriptor */
values: SrcSetValue[];
/* A value ready to use in`srcset` attribute */
attribute: string;
};
}

¥Content Collections (astro:content)

Added in: astro@2.0.0

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

¥Content collections offer APIs to configure and query your Markdown or MDX documents in src/content/. For features and usage examples, see our content collections guide.

类型:(input: CollectionConfig) => CollectionConfig

¥Type: (input: CollectionConfig) => CollectionConfig

defineCollection() 是一个用于在 src/content/config.* 文件中配置集合的实用程序。

¥defineCollection() is a utility to configure a collection in a src/content/config.* file.

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(),
}),
});
// Expose your defined collection to Astro
// with the `collections` export
export const collections = { blog };

该函数接受以下属性:

¥This function accepts the following properties:

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

¥Type: 'content' | 'data'
Default: 'content'

Added in: astro@2.5.0

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

¥type is a string that defines the type of entries stored within a collection:

  • 'content' - 适用于 Markdown (.md)、MDX (.mdx) 或 Markdoc (.mdoc) 等内容创作格式

  • 'data' - 适用于 JSON (.json) 或 YAML (.yaml) 等纯数据格式

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

¥Type: ZodType | (context: SchemaContext) => ZodType

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

¥schema is an optional Zod object to configure the type and shape of document frontmatter for a collection. Each value must use a Zod validator.

请参阅 Content Collection 指南 例如用法。

¥See the Content Collection guide for example usage.

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

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

Added in: astro@2.5.0

reference() 函数在内容配置中用于定义关系,或 “参考,” 从一个集合到另一个集合。这接受集合名称并验证内容 frontmatter 或数据文件中指定的条目标识符。

¥The reference() function is used in the content config to define a relationship, or “reference,” from one collection to another. This accepts a collection name and validates the entry identifier(s) specified in your content frontmatter or data file.

此示例定义了博客作者对 authors 集合的引用以及对同一 blog 集合的相关帖子数组:

¥This example defines references from a blog author to the authors collection and an array of related posts to the same blog collection:

import { defineCollection, reference, z } from 'astro:content';
const blog = defineCollection({
type: 'content',
schema: z.object({
// Reference a single author from the `authors` collection by `id`
author: reference('authors'),
// Reference an array of related posts from the `blog` collection by `slug`
relatedPosts: z.array(reference('blog')),
})
});
const authors = defineCollection({
type: 'data',
schema: z.object({ /* ... */ })
});
export const collections = { blog, authors };

请参阅 Content Collection 指南 例如用法。

¥See the Content Collection guide for example usage.

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

¥Type: (collection: string, filter?: (entry: CollectionEntry<TCollectionName>) => boolean) => CollectionEntry<TCollectionName>[]

getCollection() 是按集合名称检索内容集合条目列表的函数。

¥getCollection() is a function that retrieves a list of content collection entries by collection name.

它默认返回集合中的所有项目,并接受可选的 filter 函数以按条目属性缩小范围。这允许你通过 data 对象基于 idslug 或 frontmatter 值仅查询集合中的某些项目。

¥It returns all items in the collection by default, and accepts an optional filter function to narrow by entry properties. This allows you to query for only some items in a collection based on id, slug, or frontmatter values via the data object.

---
import { getCollection } from 'astro:content';
// Get all `src/content/blog/` entries
const allBlogPosts = await getCollection('blog');
// Only return posts with `draft: true` in the frontmatter
const draftBlogPosts = await getCollection('blog', ({ data }) => {
return data.draft === true;
});
---

请参阅 Content Collection 指南 例如用法。

¥See the Content Collection guide for example usage.

Added in: astro@2.5.0

类型:

¥Types:

  • (collection: string, contentSlugOrDataId: string) => CollectionEntry<TCollectionName>

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

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

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

¥getEntry() is a function that retrieves a single collection entry by collection name and either the entry id (for type: 'data' collections) or entry slug (for type: 'content' collections). getEntry() can also be used to get referenced entries to access the data, body, or render() properties:

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

有关 查询集合条目 的示例,请参阅 Content Collections 指南。

¥See the Content Collections guide for examples of querying collection entries.

Added in: astro@2.5.0

类型:

¥Types:

  • (Array<{ collection: string, id: string }>) => CollectionEntry<TCollectionName>[]

  • (Array<{ collection: string, slug: string }>) => CollectionEntry<TCollectionName>[]

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

¥getEntries() is a function that retrieves multiple collection entries from the same collection. This is useful for returning an array of referenced entries to access their associated data, body, and render() properties.

---
import { getEntries } from 'astro:content';
const enterprisePost = await getEntry('blog', 'enterprise');
// Get related posts referenced by `data.relatedPosts`
const enterpriseRelatedPosts = await getEntries(enterprisePost.data.relatedPosts);
---

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

¥Type: (collection: string, slug: string) => Promise<CollectionEntry<TCollectionName>>

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

¥getEntryBySlug() is a function that retrieves a single collection entry by collection name and entry slug.

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

请参阅 Content Collection 指南 例如用法。

¥See the Content Collection guide for example usage.

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

¥Type: (collection: string, id: string) => Promise<CollectionEntry<TCollectionName>>

Added in: astro@2.5.0

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

¥getDataEntryById() is a function that retrieves a single collection entry by collection name and entry id.

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

¥Collection Entry Type

包括 getCollection()getEntry()getEntries() 在内的查询函数均返回 CollectionEntry 类型的条目。该类型可作为 astro:content 中的实用程序使用:

¥Query functions including getCollection(), getEntry(), and getEntries() each return entries with the CollectionEntry type. This type is available as a utility from astro:content:

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

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

¥The CollectionEntry<TCollectionName> type is an object with the following values. TCollectionName is the name of the collection you’re querying (e.g. CollectionEntry<'blog'>).

可以用来:type: 'content'type: 'data' 集合示例类型:

¥Available for: type: 'content' and type: 'data' collections
Example Types:

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

  • 数据收集:'author-1' | 'author-2' | ...

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

¥A unique ID using the file path relative to src/content/[collection]. Enumerates all possible string values based on the collection entry file paths. Note that collections defined as type: 'content' include the file extension in their ID, while collections defined as type: 'data' do not.

可以用来:type: 'content'type: 'data' 集合示例类型:'blog' | 'authors' | ...

¥Available for: type: 'content' and type: 'data' collections
Example Type: 'blog' | 'authors' | ...

src/content/ 下条目所在的顶层文件夹的名称。这是用于在架构和查询函数中引用集合的名称。

¥The name of a top-level folder under src/content/ in which entries are located. This is the name used to reference the collection in your schema, and in querying functions.

可以用来:type: 'content'type: 'data' 集合类型:CollectionSchema<TCollectionName>

¥Available for: type: 'content' and type: 'data' collections
Type: CollectionSchema<TCollectionName>

从集合架构 (参见 defineCollection() 参考) 推断出的 frontmatter 属性的对象。如果未配置架构,则默认为 any

¥An object of frontmatter properties inferred from your collection schema (see defineCollection() reference). Defaults to any if no schema is configured.

可以用来:仅限 type: 'content' 集合示例类型:'entry-1' | 'entry-2' | ...

¥Available for: type: 'content' collections only
Example Type: 'entry-1' | 'entry-2' | ...

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

¥A URL-ready slug for Markdown or MDX documents. Defaults to the id without the file extension, but can be overridden by setting the slug property in a file’s frontmatter.

可以用来:仅 type: 'content' 集合类型:string

¥Available for: type: 'content' collections only
Type: string

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

¥A string containing the raw, uncompiled body of the Markdown or MDX document.

可以用来:仅 type: 'content' 集合类型:() => Promise<RenderedEntry>

¥Available for: type: 'content' collections only
Type: () => Promise<RenderedEntry>

编译给定 Markdown 或 MDX 文档以进行渲染的函数。这将返回以下属性:

¥A function to compile a given Markdown or MDX document for rendering. This returns the following properties:

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

请参阅 Content Collection 指南 例如用法。

¥See the Content Collection guide for example usage.

¥Other Content Collection Types

astro:content 模块还导出以下类型以在你的 Astro 项目中使用:

¥The astro:content module also exports the following types for use in your Astro project:

Added in: astro@3.1.0

src/content/config.* 文件中定义的所有集合名称的字符串并集。在定义接受任何集合名称的通用函数时,此类型非常有用。

¥A string union of all collection names defined in your src/content/config.* file. This type can be useful when defining a generic function that accepts any collection name.

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

Added in: astro@3.1.0

src/content/config.* 文件中定义的 type: 'content' 集合的所有名称的字符串并集。

¥A string union of all the names of type: 'content' collections defined in your src/content/config.* file.

Added in: astro@3.1.0

src/content/config.* 文件中定义的 type: 'data' 集合的所有名称的字符串并集。

¥A string union of all the names of type: 'data' collection defined in your src/content/config.* file.

defineCollection 用于 schema 函数形状的 context 对象。在为多个集合构建可重用架构时,此类型非常有用。

¥The context object that defineCollection uses for the function shape of schema. This type can be useful when building reusable schemas for multiple collections.

这包括以下属性:

¥This includes the following property:

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

Section titled 中间件(astro:middleware)

¥Middleware (astro:middleware)

Added in: astro@2.6.0

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

¥Middleware allows you to intercept requests and responses and inject behaviors dynamically every time a page or endpoint is about to be rendered. For features and usage examples, see our middleware guide.

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

¥Type: (context: APIContext, next: MiddlewareNext) => Promise<Response> | Response | Promise<void> | void

src/middleware.js 中必需的导出函数,将在渲染每个页面或 API 路由之前调用。它接收两个参数:contextnext()onRequest() 必须返回 Response:直接或通过致电 next()

¥A required exported function from src/middleware.js that will be called before rendering every page or API route. It receives two arguments: context and next(). onRequest() must return a Response: either directly, or by calling next().

src/middleware.js
export function onRequest (context, next) {
// intercept response data from a request
// optionally, transform the response
// return a Response directly, or the result of calling `next()`
return next();
};

类型:APIContext

¥Type: APIContext

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

¥The first argument of onRequest() is a context object. It mirrors many of the Astro global properties.

See Endpoint contexts for more information about the context object.

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

¥Type: (rewritePayload?: string | URL | Request) => Promise<Response>

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

¥The second argument of onRequest() is a function that calls all the subsequent middleware in the chain and returns a Response. For example, other middleware could modify the HTML body of a response and awaiting the result of next() would allow your middleware to respond to those changes.

自 Astro v4.13.0 起,next() 接受字符串、URLRequestrewrite 形式的可选 URL 路径参数,而无需重新触发新的渲染阶段。

¥Since Astro v4.13.0, next() accepts an optional URL path parameter in the form of a string, URL, or Request to rewrite the current request without retriggering a new rendering phase.

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

¥Type: (...handlers: MiddlewareHandler[]) => MiddlewareHandler

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

¥A function that accepts middleware functions as arguments, and will execute them in the order in which they are passed.

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

¥Type: (context: CreateContext) => APIContext

Added in: astro@2.8.0

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

¥A low-level API to create an APIContextto be passed to an Astro middleware onRequest() function.

集成/适配器可以使用此函数以编程方式执行 Astro 中间件。

¥This function can be used by integrations/adapters to programmatically execute the Astro middleware.

类型:(value: unknown) => string

¥Type: (value: unknown) => string

Added in: astro@2.8.0

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

¥A low-level API that takes in any value and tries to return a serialized version (a string) of it. If the value cannot be serialized, the function will throw a runtime error.

¥Internationalization (astro:i18n)

Added in: astro@3.5.0

此模块提供功能来帮助你使用项目配置的语言环境创建 URL。

¥This module provides functions to help you create URLs using your project’s configured locales.

使用 i18n 路由为你的项目创建路由将取决于你设置的影响页面路由的某些配置值。使用这些功能创建路由时,请务必考虑你的个人设置:

¥Creating routes for your project with the i18n router will depend on certain configuration values you have set that affect your page routes. When creating routes with these functions, be sure to take into account your individual settings for:

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

¥Also, note that the returned URLs created by these functions for your defaultLocale will reflect your i18n.routing configuration.

有关功能和使用示例,查看我们的 i18n 路由指南

¥For features and usage examples, see our i18n routing guide.

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

¥Type: (locale: string, path?: string, options?: GetLocaleOptions) => string

使用此函数检索区域设置的相对路径。如果区域设置不存在,Astro 会抛出错误。

¥Use this function to retrieve a relative path for a locale. If the locale doesn’t exist, Astro throws an error.

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

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

¥Type: (locale: string, path: string, options?: GetLocaleOptions) => string

当 [site] 有值时,使用此函数检索语言环境的绝对路径。如果未配置 [site],则该函数返回相对 URL。如果区域设置不存在,Astro 会抛出错误。

¥Use this function to retrieve an absolute path for a locale when [site] has a value. If [site] isn’t configured, the function returns a relative URL. If the locale doesn’t exist, Astro throws an error.

src/pages/index.astro
---
// If `site` is set to be `https://example.com`
getAbsoluteLocaleUrl("fr");
// returns https://example.com/fr
getAbsoluteLocaleUrl("fr", "");
// returns https://example.com/fr
getAbsoluteLocaleUrl("fr", "getting-started");
// returns https://example.com/fr/getting-started
getAbsoluteLocaleUrl("fr_CA", "getting-started", {
prependWith: "blog"
});
// returns https://example.com/blog/fr-ca/getting-started
getAbsoluteLocaleUrl("fr_CA", "getting-started", {
prependWith: "blog",
normalizeLocale: false
});
// returns https://example.com/blog/fr_CA/getting-started
---

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

¥Type: (path?: string, options?: GetLocaleOptions) => string[]

getRelativeLocaleUrl 这样使用它可以返回所有语言环境的相对路径列表。

¥Use this like getRelativeLocaleUrl to return a list of relative paths for all the locales.

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

¥Type: (path?: string, options?: GetLocaleOptions) => string[]

getAbsoluteLocaleUrl 这样使用它可以返回所有语言环境的绝对路径列表。

¥Use this like getAbsoluteLocaleUrl to return a list of absolute paths for all the locales.

类型:(locale: string) => string

¥Type: (locale: string) => string

配置 自定义区域设置路径 时返回与一个或多个 codes 关联的 path 的函数。

¥A function that returns the path associated to one or more codes when custom locale paths are configured.

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

类型:(path: string) => string

¥Type: (path: string) => string

返回与区域设置 path 关联的 code 的函数。

¥A function that returns the code associated to a locale path.

astro.config.mjs
export default defineConfig({
i18n: {
locales: ["es", "en", {
path: "french",
codes: ["fr", "fr-BR", "fr-CA"]
}]
}
})
src/pages/index.astro
---
getLocaleByPath("french"); // returns "fr" because that's the first code configured
---

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

¥Type: (context: APIContext, statusCode?: ValidRedirectStatus) => Promise<Response>

Added in: astro@4.6.0

返回重定向到配置的 defaultLocaleResponse 的函数。它接受可选的有效重定向状态代码。

¥A function that returns a Response that redirects to the defaultLocale configured. It accepts an optional valid redirect status code.

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>

¥Type: (context: APIContext, response: Response) => Promise<Response>

Added in: astro@4.6.0

允许你在自己的中间件中使用 i18n.fallback configuration 的函数。

¥A function that allows you to use your i18n.fallback configuration in your own middleware.

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

¥Type: (context: APIContext, response?: Response) => Promise<Response> | undefined

Added in: astro@4.6.0

在以下情况下,在路由中间件中使用此功能返回 404:

¥Use this function in your routing middleware to return a 404 when:

  • 当前路径不是根路径。例如 //<base>

  • URL 不包含语言环境

传递 Response 后,此函数发出的新 Response 将包含与原始响应相同的标头。

¥When a Response is passed, the new Response emitted by this function will contain the same headers of the original 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

¥Type: (options: { prefixDefaultLocale: boolean, redirectToDefaultLocale: boolean }) => MiddlewareHandler

Added in: astro@4.6.0

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

¥A function that allows you to programmatically create the Astro i18n middleware.

当你仍想使用默认的 i18n 逻辑,但只为你的网站添加一些例外时,这很有用。

¥This is use useful when you still want to use the default i18n logic, but add only a few exceptions to your website.

middleware.js
import { middleware } from "astro:i18n";
import { sequence, defineMiddleware } from "astro:middleware";
const customLogic = defineMiddleware(async (context, next) => {
const response = await next();
// Custom logic after resolving the response.
// It's possible to catch the response coming from Astro i18n middleware.
return response;
});
export const onRequest = sequence(customLogic, middleware({
prefixDefaultLocale: true,
redirectToDefaultLocale: false
}))

类型:(context: APIContext) => boolean

¥Type: (context: APIContext) => boolean

Added in: astro@4.6.0

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

¥Checks whether the current URL contains a configured locale. Internally, this function will use 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 });
})

查看 Transitions 客户端 API (astro:transitions/client)

Section titled 查看 Transitions 客户端 API (astro:transitions/client)

¥View Transitions client API (astro:transitions/client)

Added in: astro@3.2.0

此模块提供控制和与 View Transitions API 和客户端路由交互的功能。

¥This module provides functions to control and interact with the View Transitions API and client-side router.

有关功能和使用示例,请参阅我们的“查看转换”指南

¥For features and usage examples, see our View Transitions guide.

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

¥Type: (href: string, options?: Options) => void

Added in: astro@3.2.0

使用 View Transitions API 执行到给定 href 的导航的函数。

¥A function that executes a navigation to the given href using the View Transitions API.

此函数签名基于 来自浏览器导航 API 的 navigate 函数。尽管基于导航 API,但此功能是在 历史 API 之上实现的,以允许导航而无需重新加载页面。

¥This function signature is based on the navigate function from the browser Navigation API. Although based on the Navigation API, this function is implemented on top of the History API to allow for navigation without reloading the page.

¥history option

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

¥Type: 'auto' | 'push' | 'replace'
Default: 'auto'

Added in: astro@3.2.0

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

¥Defines how this navigation should be added to the browser history.

  • 'push':路由将使用 history.pushState 在浏览器历史记录中创建一个新条目。

  • 'replace':路由将使用 history.replaceState 更新 URL,而不添加新的导航条目。

  • 'auto'(默认):路由将尝试 history.pushState,但如果无法转换到 URL,则当前 URL 将保持不变,浏览器历史记录不会发生任何变化。

此选项遵循浏览器导航 API 中的 history 选项,但针对 Astro 项目中可能发生的情况进行了简化。

¥This option follows the history option from the browser Navigation API but simplified for the cases that can happen on an Astro project.

¥formData option

类型:FormData

¥Type: FormData

Added in: astro@3.5.0

POST 请求的 FormData 对象。

¥A FormData object for POST requests.

提供此选项后,对导航目标页面的请求将作为 POST 请求发送,其中表单数据对象作为内容。

¥When this option is provided, the requests to the navigation target page will be sent as a POST request with the form data object as the content.

提交启用视图转换的 HTML 表单将使用此方法,而不是使用页面重新加载的默认导航。调用此方法允许以编程方式触发相同的行为。

¥Submitting an HTML form with view transitions enabled will use this method instead of the default navigation with page reload. Calling this method allows triggering the same behavior programmatically.

¥info option

类型:any

¥Type: any

Added in: astro@3.6.0

此导航引起的 astro:before-preparationastro:before-swap 事件中将包含任意数据。

¥Arbitrary data to be included in the astro:before-preparation and astro:before-swap events caused by this navigation.

此选项模仿浏览器导航 API 中的 info 选项

¥This option mimics the info option from the browser Navigation API.

¥state option

类型:any

¥Type: any

Added in: astro@3.6.0

与此导航创建的 NavitationHistoryEntry 对象关联的任意数据。然后可以使用 History API 中的 history.getState function 检索此数据。

¥Arbitrary data to be associated with the NavitationHistoryEntry object created by this navigation. This data can then be retrieved using the history.getState function from the History API.

此选项模仿浏览器导航 API 中的 state 选项

¥This option mimics the state option from the browser Navigation API.

¥sourceElement option

类型:Element

¥Type: Element

Added in: astro@3.6.0

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

¥The element that triggered this navigation, if any. This element will be available in the following events:

  • astro:before-preparation

  • astro:before-swap

类型:boolean

¥Type: boolean

Added in: astro@3.2.0

当前浏览器是否支持并启用视图转换。

¥Whether or not view transitions are supported and enabled in the current browser.

类型:boolean

¥Type: boolean

Added in: astro@3.2.0

当前页面是否为客户端导航启用了视图转换。这可用于制作在具有视图转换的页面上使用时行为不同的组件。

¥Whether or not the current page has view transitions enabled for client-side navigation. This can be used to make components that behave differently when they are used on pages with view transitions.

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

¥Type: () => 'none' | 'animate' | 'swap'

Added in: astro@3.6.0

返回不支持视图转换的浏览器中使用的后备策略。

¥Returns the fallback strategy to use in browsers that do not support view transitions.

有关如何选择和配置后备行为,请参阅 回退控制 指南。

¥See the guide on Fallback control for how to choose and configure the fallback behavior.

astro:before-preparation 事件

Section titled astro:before-preparation 事件

¥astro:before-preparation event

使用视图转换在导航开始时分派的事件。此事件发生在发出任何请求和更改任何浏览器状态之前。

¥An event dispatched at the beginning of a navigation using View Transitions. This event happens before any request is made and any browser state is changed.

此事件具有以下属性:

¥This event has the attributes:

阅读有关如何在 查看转换指南 上使用此事件的更多信息。

¥Read more about how to use this event on the View Transitions guide.

astro:after-preparation 事件

Section titled astro:after-preparation 事件

¥astro:after-preparation event

使用视图转换的导航中的下一页加载后分派的事件。

¥An event dispatched after the next page in a navigation using View Transitions is loaded.

此事件没有属性。

¥This event has no attributes.

阅读有关如何在 查看转换指南 上使用此事件的更多信息。

¥Read more about how to use this event on the View Transitions guide.

¥astro:before-swap event

在解析、准备下一页并将其链接到文档以准备转换但在文档之间交换任何内容之前分派的事件。

¥An event dispatched after the next page is parsed, prepared, and linked into a document in preparation for the transition but before any content is swapped between the documents.

此事件无法取消。调用 preventDefault() 是无操作。

¥This event can’t be canceled. Calling preventDefault() is a no-op.

此事件具有以下属性:

¥This event has the attributes:

阅读有关如何在 查看转换指南 上使用此事件的更多信息。

¥Read more about how to use this event on the View Transitions guide.

¥astro:after-swap event

页面内容交换后但在视图转换结束之前分派的事件。

¥An event dispatched after the contents of the page have been swapped but before the view transition ends.

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

¥The history entry and scroll position have already been updated when this event is triggered.

¥astro:page-load event

页面完成加载后分派的事件,无论是使用视图转换的导航还是浏览器原生的导航。

¥An event dispatched after a page completes loading, whether from a navigation using view transitions or native to the browser.

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

¥When view transitions is enabled on the page, code that would normally execute on DOMContentLoaded should be changed to execute on this event.

查看 Transitions 事件属性

Section titled 查看 Transitions 事件属性

¥View Transitions events attributes

Added in: astro@3.6.0

类型:URL

¥Type: URL

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

¥Arbitrary data defined during navigation.

这是在 navigate() 功能info 选项 上传递的字面量值。

¥This is the literal value passed on the info option of the navigate() function.

类型:Element | undefined

¥Type: Element | undefined

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

¥The element that triggered the navigation. This can be, for example, an <a> element that was clicked.

使用 navigate() 功能 时,这将是调用中指定的元素。

¥When using the navigate() function, this will be the element specified in the call.

类型:Document

¥Type: Document

导航中下一页的文档。此文档的内容将替换当前文档的内容。

¥The document for the next page in the navigation. The contents of this document will be swapped in place of the contents of the current document.

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

¥Type: 'push' | 'replace' | 'traverse'

正在发生哪种历史导航。

¥Which kind of history navigation is happening.

  • push:正在为新页面创建新的 NavigationHistoryEntry

  • replace:当前 NavigationHistoryEntry 将被新页面的条目替换。

  • traverse:未创建 NavigationHistoryEntry。历史记录中的位置正在发生变化。遍历的方向在 direction 属性 上给出

类型:Direction

¥Type: Direction

转换的方向。

¥The direction of the transition.

  • forward:导航到历史记录中的下一页或新页面。

  • back:导航到历史记录中的上一页。

  • 其他监听器可能设置的任何其他内容。

类型:URL

¥Type: URL

启动导航的页面的 URL。

¥The URL of the page initiating the navigation.

类型:URL

¥Type: URL

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

¥The URL of the page being navigated to. This property can be modified, the value at the end of the lifecycle will be used in the NavigationHistoryEntry for the next page.

类型:FormData | undefined

¥Type: FormData | undefined

POST 请求的 FormData 对象。

¥A FormData object for POST requests.

设置此属性后,将向 to URL 发送 POST 请求,其中给定的表单数据对象作为内容,而不是正常的 GET 请求。

¥When this attribute is set, a POST request will be sent to the to URL with the given form data object as the content instead of the normal GET request.

提交启用了视图转换的 HTML 表单时,此字段会自动设置为表单中的数据。使用 navigate() 功能 时,此值与选项中给出的值相同。

¥When submitting an HTML form with view transitions enabled, this field is automatically set to the data in the form. When using the navigate() function, this value is the same as given in the options.

类型:() => Promise<void>

¥Type: () => Promise<void>

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

¥Implementation of the following phase in the navigation (loading the next page). This implementation can be overridden to add extra behavior.

类型:ViewTransition

¥Type: ViewTransition

此导航中使用的视图转换对象。在不支持 视图转换 API 的浏览器上,这是一个为方便起见实现相同 API 的对象,但没有 DOM 集成。

¥The view transition object used in this navigation. On browsers that do not support the View Transitions API, this is an object implementing the same API for convenience but without the DOM integration.

类型:() => void

¥Type: () => void

文档交换逻辑的实现。

¥Implementation of the document swap logic.

阅读有关如何在 View Transitions 指南中使用 构建你自己的自定义交换函数 的更多信息。

¥Read more on how to build your own custom swap function on the View Transitions guide.

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

¥By default, this implementation will call the following functions in order:

类型:(newDocument: Document) => void

¥Type: (newDocument: Document) => void

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

¥Marks scripts in the new document that should not be executed. Those scripts are already in the current document and are not flagged for re-execution using data-astro-rerun.

类型:(newDocument: Document) => void

¥Type: (newDocument: Document) => void

在文档根之间交换属性,如 lang 属性。这还包括 Astro 注入的内部属性,如 data-astro-transition,这使得转换方向可用于 Astro 生成的 CSS 规则。

¥Swaps the attributes between the document roots, like the lang attribute. This also includes Astro-injected internal attributes like data-astro-transition, which makes the transition direction available to Astro-generated CSS rules.

制作自定义交换函数时,调用此函数很重要,以免破坏视图转换的动画。

¥When making a custom swap function, it is important to call this function so as not to break the view transition’s animations.

类型:(newDocument: Document) => void

¥Type: (newDocument: Document) => void

从当前文档的 <head> 中删除未保留到新文档的每个元素。然后将新文档的 <head> 中的所有新元素附加到当前文档的 <head>

¥Removes every element from the current document’s <head> that is not persisted to the new document. Then appends all new elements from the new document’s <head> to the current document’s <head>.

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

¥Type: () => () => void

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

¥Stores the element in focus on the current page and returns a function that when called, if the focused element was persisted, returns the focus to it.

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

¥Type: (newBody: Element, oldBody: Element) => void

用新主体替换旧主体。然后,遍历旧主体中应保留的每个元素,并在新主体中具有匹配的元素,然后将旧元素交换回原位。

¥Replaces the old body with the new body. Then, goes through every element in the old body that should be persisted and have a matching element in the new body and swaps the old element back in place.

¥Actions (astro:actions)

Added in: astro@4.15.0

操作可帮助你构建可从客户端代码和 HTML 表单调用的类型安全后端。定义和调用操作的所有实用程序都由 astro:actions 模块公开。有关示例和使用说明,请参阅 请参阅“操作”指南

¥Actions help you build a type-safe backend you can call from client code and HTML forms. All utilities to define and call actions are exposed by the astro:actions module. For examples and usage instructions, see the Actions guide.

Added in: astro@4.15.0

defineAction() 实用程序用于从 src/actions/index.ts 文件定义新操作。这接受包含要运行的服务器逻辑的 handler() 函数,以及可选的 input 属性以在运行时验证输入参数。

¥The defineAction() utility is used to define new actions from the src/actions/index.ts file. This accepts a handler() function containing the server logic to run, and an optional input property to validate input parameters at runtime.

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

¥handler() property

类型:(input, context) => any

¥Type: (input, context) => any

defineAction() 需要一个 handler() 函数,其中包含在调用操作时运行的服务器逻辑。从处理程序返回的数据会自动序列化并发送给调用者。

¥defineAction() requires a handler() function containing the server logic to run when the action is called. Data returned from the handler is automatically serialized and sent to the caller.

handler() 以用户输入作为其第一个参数进行调用。如果设置了 input 验证器,则在将用户输入传递给处理程序之前,将对其进行验证。第二个参数是一个 context 对象,包含 Astro 的大部分 标准端点上下文,但不包括 getActionResult()callAction()redirect()

¥The handler() is called with user input as its first argument. If an input validator is set, the user input will be validated before being passed to the handler. The second argument is a context object containing most of Astro’s standard endpoint context, excluding getActionResult(), callAction(), and redirect().

使用 贬值库 解析返回值。这支持 JSON 值和 Date()Map()Set()URL() 的实例。

¥Return values are parsed using the devalue library. This supports JSON values and instances of Date(), Map(), Set(), and URL().

¥input validator

类型:ZodType | undefined

¥Type: ZodType | undefined

可选的 input 属性接受 Zod 验证器以在运行时验证处理程序输入。如果操作验证失败,则返回 BAD_REQUEST 错误,并且不会调用 handler

¥The optional input property accepts a Zod validator to validate handler inputs at runtime. If the action fails to validate, a BAD_REQUEST error is returned and the handler is not called.

如果省略 inputhandler 将接收 JSON 请求的 unknown 类型输入和表单请求的 FormData 类型输入。

¥If input is omitted, the handler will receive an input of type unknown for JSON requests and type FormData for form requests.

¥Use with accept: 'form'

如果你的操作接受表单输入,请使用 z.object() 验证器自动将表单数据解析为类型化对象。表单数据字段支持以下验证器:

¥If your action accepts form inputs, use the z.object() validator to automatically parse form data to a typed object. The following validators are supported for form data fields:

  • 可以使用 z.number() 验证类型为 number 的输入

  • 可以使用 z.boolean() 验证类型为 checkbox 的输入

  • 可以使用 z.instanceof(File) 验证类型为 file 的输入

  • 可以使用 z.array(/* validator */) 验证相同 name 的多个输入

  • 所有其他输入都可以使用 z.string() 进行验证

z.object() 验证器还支持扩展函数,包括 .refine().transform().pipe()

¥Extension functions including .refine(), .transform(), and .pipe() are also supported on the z.object() validator.

要应用不同验证器的联合,请使用 z.discriminatedUnion() 封装器根据特定表单字段缩小类型。此示例接受向 “create” 或 “update” 用户提交的表单,使用名为 type 的表单字段来确定要针对哪个对象进行验证:

¥To apply a union of different validators, use the z.discriminatedUnion() wrapper to narrow the type based on a specific form field. This example accepts a form submission to either “create” or “update” a user, using the form field with the name type to determine which object to validate against:

import { defineAction } from 'astro:actions';
import { z } from 'astro:schema';
export const server = {
changeUser: defineAction({
accept: 'form',
input: z.discriminatedUnion('type', [
z.object({
// Matches when the `type` field has the value `create`
type: z.literal('create'),
name: z.string(),
email: z.string().email(),
}),
z.object({
// Matches when the `type` field has the value `update`
type: z.literal('update'),
id: z.number(),
name: z.string(),
email: z.string().email(),
}),
]),
async handler(input) {
if (input.type === 'create') {
// input is { type: 'create', name: string, email: string }
} else {
// input is { type: 'update', id: number, name: string, email: string }
}
},
}),
};

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

¥Type: (error?: unknown | ActionError) => boolean

Added in: astro@4.15.0

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

¥The isInputError() utility is used to check whether an ActionError is an input validation error. When the input validator is a z.object(), input errors include a fields object with error messages grouped by name.

See the form input errors guide for more on using isInputError().

Added in: astro@4.15.0

ActionError() 构造函数用于创建由操作 handler 抛出的错误。这接受一个描述所发生错误的 code 属性(例如:"UNAUTHORIZED"),以及一个包含更多详细信息的可选 message 属性。

¥The ActionError() constructor is used to create errors thrown by an action handler. This accepts a code property describing the error that occurred (example: "UNAUTHORIZED"), and an optional message property with further details.

Added in: astro@4.15.0

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

¥The code property accepts human-readable versions of all HTTP status codes. The following codes are supported:

  • BAD_REQUEST (400):客户端发送了无效输入。当操作 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):服务器不支持请求的媒体类型。注意:操作已经检查了 Content-Type 标头 的 JSON 和表单请求,因此你可能不需要手动引发此代码。

  • 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):服务器从上游服务器收到超时。

Added in: astro@4.15.0

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

¥The message property accepts a string. (e.g. “User must be logged in.“)

Astro 中文网 - 粤ICP备13048890号