跳转到内容

在 Astro 组件间共享状态

在构建 Astro 网站时,你可能需要在多个组件之间共享状态。Astro 推荐使用 Nano Stores 来进行共享客户端存储。

  1. 安装 Nano Stores

    终端窗口
    npm install nanostores
  2. 创建一个 store。在本例中,该 store 用于跟踪对话框是否打开。

    src/store.js
    import { atom } from 'nanostores';
    export const isOpen = atom(false);
  3. 在将要共享状态的组件中,在 <script> 标签内导入并使用该 store。

    下面的 ButtonDialog 组件都使用共享的 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 clicked
    function openDialog() {
    isOpen.set(true);
    }
    // Add an event listener to the button
    document.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 accordingly
    isOpen.subscribe(open => {
    if (open) {
    document.getElementById('dialog').style.display = 'block';
    } else {
    document.getElementById('dialog').style.display = 'none';
    }
    })
    </script>
贡献 社区 赞助