Share state between Astro components
本頁內容尚未翻譯。
:::tipUsing framework components? See how to share state between Islands!:::
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
Install Nano Stores:
npm install nanostorespnpm add nanostoresyarn add nanostoresCreate a store. In this example, the store tracks whether a dialog is open or not:
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:<button id="openDialog">Open</button> <script> import { isOpen } from '../store.js'; // Set the store to true when the button is clicked function openDialog() { isOpen.set(true); } // Add an event listener to the button document.getElementById('openDialog').addEventListener('click', openDialog); </script><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 accordingly isOpen.subscribe(open => { if (open) { document.getElementById('dialog').style.display = 'block'; } else { document.getElementById('dialog').style.display = 'none'; } }) </script>