Skip to content

脚本和事件处理

你可以使用标准 HTML <script> 标签向没有 使用 UI 框架 的 Astro 组件(如 React、Svelte、Vue 等)添加交互性。这允许你发送 JavaScript 以在浏览器中运行并向 Astro 组件添加功能。

¥You can add interactivity to your Astro components without using a UI framework like React, Svelte, Vue, etc. using standard HTML <script> tags. This allows you to send JavaScript to run in the browser and add functionality to your Astro components.

¥Client-Side Scripts

脚本可用于添加事件监听器、发送分析数据、播放动画以及 JavaScript 可以在网络上执行的所有其他操作。

¥Scripts can be used to add event listeners, send analytics data, play animations, and everything else JavaScript can do on the web.

src/components/ConfettiButton.astro
<button data-confetti-button>Celebrate!</button>
<script>
// Import npm modules.
import confetti from 'canvas-confetti';
// Find our component DOM on the page.
const buttons = document.querySelectorAll('[data-confetti-button]');
// Add event listeners to fire confetti when a button is clicked.
buttons.forEach((button) => {
button.addEventListener('click', () => confetti());
});
</script>

默认情况下,Astro 处理并打包 <script> 标签,添加对导入 npm 模块、编写 TypeScript 等的支持。

¥By default, Astro processes and bundles <script> tags, adding support for importing npm modules, writing TypeScript, and more.

¥Using <script> in Astro

.astro 文件中,你可以通过添加一个(或多个)<script> 标签来添加客户端 JavaScript。

¥In .astro files, you can add client-side JavaScript by adding one (or more) <script> tags.

在此示例中,将 <Hello /> 组件添加到页面将向浏览器控制台记录一条消息。

¥In this example, adding the <Hello /> component to a page will log a message to the browser console.

src/components/Hello.astro
<h1>Welcome, world!</h1>
<script>
console.log('Welcome, browser console!');
</script>

¥Script processing

默认情况下,<script> 标签由 Astro 处理。

¥By default, <script> tags are processed by Astro.

  • 任何导入都将被打包,允许你导入本地文件或节点模块。

  • 处理后的脚本将注入到使用 type="module" 声明的位置。

  • 完全支持 TypeScript,包括导入 TypeScript 文件。

  • 如果你的组件在页面上多次使用,则该脚本将仅包含一次。

src/components/Example.astro
<script>
// Processed! Bundled! TypeScript-supported!
// Importing local scripts and Node modules works.
</script>

type="module" 属性使浏览器将脚本视为 JavaScript 模块。这有几个性能优势:

¥The type="module" attribute makes the browser treat the script as a JavaScript module. This has several performance benefits:

  • 渲染不会被阻止。当模块脚本及其依赖加载时,浏览器继续处理 HTML 的其余部分。

  • 浏览器在执行模块脚本之前等待 HTML 被处理。你不需要监听 “load” 事件。

  • asyncdefer 属性是不必要的。模块脚本总是被推迟。

¥Opting out of processing

要阻止 Astro 处理脚本,请添加 is:inline 指令。

¥To prevent Astro from processing a script, add the is:inline directive.

src/components/InlineScript.astro
<script is:inline>
// Will be rendered into the HTML exactly as written!
// Local imports are not resolved and will not work.
// If in a component, repeats each time the component is used.
</script>
See our directives reference page for more information about the directives available on <script> tags.

在你的页面上包含 JavaScript 文件

标题部分 在你的页面上包含 JavaScript 文件

¥Include JavaScript files on your page

你可能希望将脚本编写为单独的 .js/.ts 文件,或者需要引用另一台服务器上的外部脚本。你可以通过在 <script> 标签的 src 属性中引用这些来完成此操作。

¥You may want to write your scripts as separate .js/.ts files or need to reference an external script on another server. You can do this by referencing these in a <script> tag’s src attribute.

¥Import local scripts

何时使用这个:当你的脚本位于 src/ 内时。

¥When to use this: when your script lives inside of src/.

Astro 将按照 脚本处理规则.1 构建、优化这些脚本并将其添加到页面中。

¥Astro will build, optimize, and add these scripts to the page for you, following its script processing rules.

src/components/LocalScripts.astro
<!-- relative path to script at `src/scripts/local.js` -->
<script src="../scripts/local.js"></script>
<!-- also works for local TypeScript files -->
<script src="./script-with-types.ts"></script>

¥Load external scripts

何时使用这个:当你的 JavaScript 文件位于 public/ 内或 CDN 上时。

¥When to use this: when your JavaScript file lives inside of public/ or on a CDN.

要加载项目 src/ 文件夹外部的脚本,请包含 is:inline 指令。当你如上所述导入脚本时,此方法会跳过 Astro 提供的 JavaScript 处理、打包和优化。

¥To load scripts outside of your project’s src/ folder, include the is:inline directive. This approach skips the JavaScript processing, bundling, and optimizations that are provided by Astro when you import scripts as described above.

src/components/ExternalScripts.astro
<!-- absolute path to a script at `public/my-script.js` -->
<script is:inline src="/my-script.js"></script>
<!-- full URL to a script on a remote server -->
<script is:inline src="https://my-analytics.com/script.js"></script>

¥Common script patterns

处理 onclick 和其他事件

标题部分 处理 onclick 和其他事件

¥Handle onclick and other events

一些 UI 框架使用自定义语法进行事件处理,例如 onClick={...} (React/Preact) 或 @click="..." (Vue)。Astro 更严格地遵循标准 HTML,并且不使用事件的自定义语法。

¥Some UI frameworks use custom syntax for event handling like onClick={...} (React/Preact) or @click="..." (Vue). Astro follows standard HTML more closely and does not use custom syntax for events.

相反,你可以在 <script> 标记中使用 addEventListener 来处理用户交互。

¥Instead, you can use addEventListener in a <script> tag to handle user interactions.

src/components/AlertButton.astro
<button class="alert">Click me!</button>
<script>
// Find all buttons with the `alert` class on the page.
const buttons = document.querySelectorAll('button.alert');
// Handle clicks on each button.
buttons.forEach((button) => {
button.addEventListener('click', () => {
alert('Button was clicked!');
});
});
</script>

具有自定义元素的 Web 组件

标题部分 具有自定义元素的 Web 组件

¥Web components with custom elements

你可以使用 Web 组件标准创建具有自定义行为的自己的 HTML 元素。在 .astro 组件中定义 自定义元素 允许你构建交互式组件,而无需 UI 框架库。

¥You can create your own HTML elements with custom behavior using the Web Components standard. Defining a custom element in a .astro component allows you to build interactive components without needing a UI framework library.

在此示例中,我们定义了一个新的 <astro-heart> HTML 元素,用于跟踪你单击心形按钮的次数并使用最新计数更新 <span>

¥In this example, we define a new <astro-heart> HTML element that tracks how many times you click the heart button and updates the <span> with the latest count.

src/components/AstroHeart.astro
<!-- Wrap the component elements in our custom element “astro-heart”. -->
<astro-heart>
<button aria-label="Heart">💜</button> × <span>0</span>
</astro-heart>
<script>
// Define the behaviour for our new type of HTML element.
class AstroHeart extends HTMLElement {
connectedCallback() {
let count = 0;
const heartButton = this.querySelector('button');
const countSpan = this.querySelector('span');
// Each time the button is clicked, update the count.
heartButton.addEventListener('click', () => {
count++;
countSpan.textContent = count.toString();
});
}
}
// Tell the browser to use our AstroHeart class for <astro-heart> elements.
customElements.define('astro-heart', AstroHeart);
</script>

在这里使用自定义元素有两个优点:

¥There are two advantages to using a custom element here:

  1. 你可以使用 this.querySelector(),而不是使用 document.querySelector() 搜索整个页面,它仅在当前自定义元素实例内搜索。这使得一次只处理一个组件实例的子组件变得更加容易。

  2. 虽然 <script> 只运行一次,但浏览器每次在页面上找到 <astro-heart> 时都会运行我们自定义元素的 constructor() 方法。这意味着你可以一次安全地为一个组件编写代码,即使你打算在一页上多次使用该组件。

将 frontmatter 变量传递给脚本

标题部分 将 frontmatter 变量传递给脚本

¥Pass frontmatter variables to scripts

在 Astro 组件中,--- 栅栏之间的 前题 中的代码在服务器上运行,并且在浏览器中不可用。要将变量从服务器发送到客户端,我们需要一种方法来存储变量,然后在浏览器中运行 JavaScript 时读取它们。

¥In Astro components, the code in the frontmatter between the --- fences runs on the server and is not available in the browser. To send variables from the server to the client, we need a way to store our variables and then read them when JavaScript runs in the browser.

一种方法是使用 data-* 属性 在 HTML 输出中存储变量的值。一旦 HTML 在浏览器中加载,脚本(包括自定义元素)就可以使用元素的 dataset 属性读取这些属性。

¥One way to do this is to use data-* attributes to store the value of variables in your HTML output. Scripts, including custom elements, can then read these attributes using an element’s dataset property once your HTML loads in the browser.

在此示例组件中,message 属性存储在 data-message 属性中,因此自定义元素可以读取 this.dataset.message 并在浏览器中获取该属性的值。

¥In this example component, a message prop is stored in a data-message attribute, so the custom element can read this.dataset.message and get the value of the prop in the browser.

src/components/AstroGreet.astro
---
const { message = 'Welcome, world!' } = Astro.props;
---
<!-- Store the message prop as a data attribute. -->
<astro-greet data-message={message}>
<button>Say hi!</button>
</astro-greet>
<script>
class AstroGreet extends HTMLElement {
connectedCallback() {
// Read the message from the data attribute.
const message = this.dataset.message;
const button = this.querySelector('button');
button.addEventListener('click', () => {
alert(message);
});
}
}
customElements.define('astro-greet', AstroGreet);
</script>

现在我们可以多次使用我们的组件,并且每次都会收到不同的消息。

¥Now we can use our component multiple times and be greeted by a different message for each one.

src/pages/example.astro
---
import AstroGreet from '../components/AstroGreet.astro';
---
<!-- Use the default message: “Welcome, world!” -->
<AstroGreet />
<!-- Use custom messages passed as a props. -->
<AstroGreet message="Lovely day to build components!" />
<AstroGreet message="Glad you made it! 👋" />

¥Combining scripts and UI Frameworks

执行 <script> 标记时,UI 框架渲染的元素可能尚不可用。如果你的脚本还需要处理 UI 框架组件,建议使用自定义元素。

¥Elements rendered by a UI framework may not be available yet when a <script> tag executes. If your script also needs to handle UI framework components, using a custom element is recommended.

Astro 中文网 - 粤ICP备13048890号