使用Alpine JS Persist插件实现页面刷新后保留深色模式开关状态求助
深色模式持久化修改方案
你只需要对现有代码做2处简单修改,即可实现深色模式选择本地保存,刷新页面不会重置:
- 替换原有Alpine JS引入代码,新增Persist插件支持
- 修改darkMode变量的声明逻辑,开启持久化存储
完整可直接替换的代码
<script src="//unpkg.com/alpinejs" defer></script> <script src="//unpkg.com/@alpinejs/persist@3.x.x/dist/cdn.min.js" defer></script> <style> .darkmode-switcher { width: 64px; height: 32px; border-radius: 80px; display: flex; flex-direction: row; align-items: center; justify-content: flex-start; padding: 2px; cursor: pointer; background-color: #191919; transition: 0.3s all ease-in-out; } .darkmode-switcher__circle { width: 28px; height: 28px; border-radius: 80px; background-color: white; transition: 0.3s all ease-in-out; } </style> <div class="mode-switcher" x-data="{ darkMode: $persist(false), switchMode: function() { this.darkMode = !this.darkMode } }"> <div class="darkmode-switcher" @click="switchMode()"> <div class="darkmode-switcher__circle"></div> </div> <template x-if="darkMode"> <style> .darkmode-switcher { background-color: white; } .darkmode-switcher__circle { background-color: black; transform: translateX(32px); } .content-wrapper { background-color: black; } .content { color: white; background-color: #191919; } body { background-color: black; } </style> </template> </div>
修改说明
- 新增了一行Persist插件的引入代码,不需要额外配置,加载后Alpine会自动识别该插件
- 原有
x-data中的darkMode: false修改为darkMode: $persist(false),变量的值会自动保存在用户本地浏览器存储中,刷新页面时会自动读取之前保存的选择,不需要用户重新切换
内容的提问来源于stack exchange,提问作者Leo Guo
相关产品推荐
相关产品推荐

