🏎 Давайте начнем
Обновлять конфигурацию Tailwind, чтобы она знала, что нужно переключить темный режим в зависимости от класса.
// tailwind.config.js
module.exports = {
darkMode: 'class',
// ...
}
Это позволит вам писать bg-gray-50 dark:bg-black
и показывать цвета фона в зависимости от текущего режима.
<html class="dark">
<body>
<div class="bg-gray-100 dark:bg-gray-600">
<!-- ... -->
</div>
</body>
</html>
Теперь давайте попробуем удалить этот жестко закодированный dark
класс в html
теге и извлечь значение из localStorage
использования Alpine
<html
x-data="{ darkMode: localStorage.getItem('dark') === 'true'} "
x-init="$watch('darkMode', val => localStorage.setItem('dark', val))"
x-bind:class="{ 'dark': darkMode }"
>
🤔 Wait, what's going on here?
x-data="{ darkMode: localStorage.getItem('dark') === 'true' "
x-data
tells the framework to initialize a new component with the following data object. In our case, the object is:
{ darkMode: localStorage.getItem('dark') === 'true'}
Я думаю о нем как о простой переменной и устанавливаю darkMode
true
значение любого или false
на основе значения элемента dark
localStorage.
x-init="$watch('darkMode', val => localStorage.setItem('dark', val))"
$watch
is a magic property (yup, that's the official terminology 😁) in Alpine used to watch data we have and trigger a function.x-init
You might have already guessed it. It runs an expression when a component is initialized.
Так хорошо до сих пор? Если нет, дайте мне знать. Я постараюсь уточнить в комментариях и соответствующим образом
обновить этот пост Давайте добавим кнопку, чтобы переключить тему сейчас.
<button @click="darkMode = !darkMode">
Toggle Theme
</button>
🏁 Yup, that's all you need 😎
Вот отполированная версия, которую я использовал в HIGHSCORE.domains
Это мой первый раз, когда я использую AlpineJS и был показан в Alpine.js Weekly #61 от @hugo__df
highscore.domains получил переключатель темного режима на базе Alpine и TailwindUI от @onerinas
Оставьте здесь несколько ссылок, которые могут быть полезны, если вы хотите попробовать это в своем проекте:
TailwindCSS:
- https://tailwindcss.com/docs/installation
- https://tailwindcss.com/docs/dark-mode#toggling-dark-mode-manually
AlpineJS:
x-init
Runs an expression when a component is initialized.
https://github.com/alpinejs/alpine#x-init
x-data
Declares a new component scope.
https://github.com/alpinejs/alpine#x-data
x-bind
Sets the value of an attribute to the result of a JS expression.
https://github.com/alpinejs/alpine#x-bind
$watch
Will fire a provided callback when a component property you "watched" gets changed.
https://github.com/alpinejs/alpine#watch