在 Astro 组件间共享状态
正在使用框架组件?请参阅如何在 Islands 之间共享状态!
在构建 Astro 网站时,你可能需要在多个组件之间共享状态。Astro 推荐使用 Nano Stores 来进行共享客户端存储。
-
安装 Nano Stores
终端窗口 npm install nanostores终端窗口 pnpm add nanostores终端窗口 yarn add nanostores -
创建一个 store。在本例中,该 store 用于跟踪对话框是否打开。
src/store.js import { atom } from 'nanostores';export const isOpen = atom(false); -
在将要共享状态的组件中,在
<script>
标签内导入并使用该 store。下面的
Button
和Dialog
组件都使用共享的isOpen
状态来控制某个特定的<div>
是隐藏还是显示。src/components/Button.astro <button id="openDialog">Open</button><script>import { isOpen } from '../store.js';// Set the store to true when the button is clickedfunction openDialog() {isOpen.set(true);}// Add an event listener to the buttondocument.getElementById('openDialog').addEventListener('click', openDialog);</script>src/components/Dialog.astro <div id="dialog" style="display: none">Hello world!</div><script>import { isOpen } from '../store.js';// Listen to changes in the store, and show/hide the dialog accordinglyisOpen.subscribe(open => {if (open) {document.getElementById('dialog').style.display = 'block';} else {document.getElementById('dialog').style.display = 'none';}})</script>