AlpineJS x-show 不会随着状态变化而更新

时间:2021-03-08 08:09:51

标签: laravel-8 alpine.js

我遇到了一个问题,我有一个通知面板,当点击按钮时应该打开该面板。当我点击按钮时,没有任何反应。控制台也没有错误。

<body>
    <div x-data="Setup()">
        <button
        @click="isNotificationsPanelOpen=true"
        >BUTTON</button>

        <section
        x-ref="notificationsPanel"
        x-show="isNotificationsPanelOpen"
        @keydown.escape="isNotificationsPanelOpen=false">
            NOTIFICATIONS PANEL
        </section>
    </div>

    <script>
    function Setup()
    {
        return {
            loading: true,
            isNotificationsPanelOpen: false,
            openNotificationsPanel() {
                this.isNotificationsPanelOpen = true;
                console.log('openNotificationsPanel called');
                console.log(this.isNotificationsPanelOpen);
                this.$nextTick(() => {
                    this.$refs.notificationsPanel.focus()
                })
            }
        }
    }
    </script>

    @stack('modals')

    @livewireScripts
</body>

我也尝试使用 @click="isNotificationsPanelOpen=true" 而不是使用 @click="openNotificationsPanel",我通过这样做看到了 console.log 消息,但面板仍然保持为 display:none

我对 AlpineJS 还很陌生,但我相信这应该可行,有人能告诉我为什么不可行吗?

1 个答案:

答案 0 :(得分:0)

当我尝试此代码时,它可以正常工作,但正在重新加载页面。

您可以通过将 .prevent 添加到 @click 事件来停止重新加载。

 <button @click.prevent="isNotificationsPanelOpen=true">
   BUTTON
 </button>