Alpine Modal 在页面加载时打开,但随机数关闭在新页面加载时无法打开



我有一些问题与$persist插件。我的模态打开页面加载如预期。但是,当我关闭模态并转到另一个页面时,我不希望它再次打开。

https://codepen.io/createsean/pen/MWQOvpx上面的Codepen显示了工作模式,但这在所有页面加载时都加载- javascript在页面加载时单击隐藏按钮。

我想做的是在第一页加载时显示模态,然后随后的页面加载不显示。我认为我需要使用$persist插件和$store magic

然而,我无法弄清楚如何得到这个工作,请建议。

HTML

<div x-data="{ noticeModal: $persist(false).as('notice-modal').using(sessionStorage) }" class="flex justify-center">
<!-- Trigger -->
<span x-on:click="noticeModal = true" id="open-notice-modal" class="hidden">
<button type="button" class="bg-white px-5 py-2.5 rounded-md shadow">
Open dialog
</button>
</span>
<p class="my-12 text-2xl max-w-2xl mx-auto">A hidden button gets clicked on page load + 2 seconds and opens the modal. But it does it on every page load, when it should only be on first page load.</p>
<!-- Modal -->
<div
x-show="noticeModal"
style="display: none"
x-on:keydown.escape.prevent.stop="noticeModal = false"
role="dialog"
aria-modal="true"
x-id="['modal-title']"
:aria-labelledby="$id('modal-title')"
class="fixed inset-0 z-50 max-w-lg mx-auto overflow-y-auto"
x-transition:enter.duration.300ms
x-transition:leave.duration.200ms>
<!-- Overlay -->
<div x-show="open" x-transition.opacity class="fixed inset-0 bg-black bg-opacity-50"></div>
<!-- Panel -->
<div
x-show="open" x-transition
x-on:click="noticeModal = false"
class="relative flex items-center justify-center min-h-screen p-4">
<div
x-on:click.stop
x-trap.noscroll.inert="noticeModal"
class="relative w-full max-w-2xl p-12 overflow-y-auto bg-white shadow-lg">
<!-- Title -->
<h2 class="mt-4 mb-4 text-3xl font-bold text-center uppercase text-pinkBrand" :id="$id('modal-title')">My Title</h2>
<!-- Content -->
<div class="prose">
some copy here
</div><!-- /.prose -->
<button
type="button"
x-on:click="noticeModal = false"
class="absolute top-4 right-4">
X
</button>
</div>
</div>
</div>
</div>

javascript

// wait for dom to load then click the button that triggers the modal
document.addEventListener("DOMContentLoaded", function(event) {
let pagebutton= document.getElementById("open-notice-modal");
// load modal after 2 seconds
setTimeout(() => {
pagebutton.click();
}, "2000")
});

您应该在sessionStorage中创建一个独立的状态变量,它只跟踪模态窗口是否打开。我们称它为noticeModalOpened。在x-init属性中(因此我们不必编写额外的JS),我们首先从sessionStorage检查noticeModalOpened状态变量,并仅在第一个页面加载时排队打开事件。在打开事件之后,我们也会翻转这个状态变量,这样下次我们就不会再打开模态了。

<div x-data="{ noticeModal: false, noticeModalOpened: $persist(false).as('notice-modal').using(sessionStorage) }"
x-init="if (!noticeModalOpened) {setTimeout(() => {noticeModal = true, noticeModalOpened = true}, 2000)}">
<!-- Trigger -->
<span @click="noticeModal = true, noticeModalOpened = true" id="open-notice-modal">
<button type="button" class="bg-white px-5 py-2.5 rounded-md shadow">
Open dialog
</button>
</span>
<!-- Modal -->
</div>

相关内容

  • 没有找到相关文章

最新更新