Share state between Astro components
Ta treść nie jest jeszcze dostępna w Twoim języku.
When building an Astro website, you may need to share state across components. Astro recommends the use of Nano Stores for shared client storage.
Recipe
Section titled “Recipe”-
Install Nano Stores:
Terminal window npm install nanostoresTerminal window pnpm add nanostoresTerminal window yarn add nanostores -
Create a store. In this example, the store tracks whether a dialog is open or not:
src/store.js import { atom } from 'nanostores';export const isOpen = atom(false); -
Import and use the store in a
<script>tag in the components that will share state.The following
ButtonandDialogcomponents each use the sharedisOpenstate to control whether a particular<div>is hidden or displayed: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";const dialog = document.getElementById("dialog");// Listen to changes in the store, and show/hide the dialog accordinglyisOpen.subscribe((open) => {if (dialog) {if (open) {dialog.style.display = "block";} else {dialog.style.display = "none";}}});</script>