【发布时间】:2022-01-12 18:43:12
【问题描述】:
我使用 TailwindCSS 和 AplineJS 构建了以下内容。 当切换开关正确保存 localStorage。但是当页面刷新时,本地存储棒并且是正确的,但是切换到默认阶段。
我在 Github 帮助页面上询问过,他们友好地说我需要使用 AlpineJS Persist...https://alpinejs.dev/plugins/persist
这是他们的回复。
您可能只想考虑使用 Persist 插件 https://alpinejs.dev/plugins/persist。你可以看到这个例子处理了这种情况,如果你想直接使用 localStorage,你可以在 x-init 上设置它。
在 x-init 中,您只需从本地存储中获取值并设置它(如果是)
好吧,我不知道如何将它们组合在一起,我是开发新手,甚至是 Alpine 的新手。如果有人能指出正确的方向,我将不胜感激。
非常感谢。
https://codepen.io/williamharvey/pen/xxXaJgM
<div
class="flex w-full items-center bg-gray-100 border-b border-gray-200 px-5 py-3 text-sm"
x-data="{ cookieConsent1: localStorage.getItem('cookieConsent1') === 'true'} "
x-init="$watch('!cookieConsent1', val => localStorage.setItem('cookieConsent1', val))">
<div class="flex-1">
<p>Cookies that remember your settings</p>
</div>
<div class="w-10 text-right">
<button type="button"
class="relative inline-flex flex-shrink-0 h-6 w-11 border-2 border-transparent rounded-full cursor-pointer transition-colors ease-in-out duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-300 bg-gray-200"
x-data="{ on: true }"
@click="on = !on;cookieConsent1 = !cookieConsent1"
x-state:on="Not Enabled"
x-state:off="Enabled"
:class="{ 'bg-green-400': on, 'bg-gray-200': !(on) }">
<span class="pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow transform ring-0 transition ease-in-out duration-200 translate-x-0" x-state:on="Enabled" x-state:off="Not Enabled" :class="{ 'translate-x-5': on, 'translate-x-0': !(on) }"></span>
</button>
</div>
</div>
【问题讨论】:
标签: javascript tailwind-css alpine.js