Back to Blog
EY

GYBEX

@gybex_enock

 

1 min read

Dark Mode Made Easy with VueUse

  • #vue
  • #tailwind
Dark Mode Made Easy with VueUse

Dark mode isn't just a trend—it's a lifestyle. Some people are so committed to it that they install browser extensions just to force dark mode on sites that don't support it; how about making it easier for them?. Dark mode helps reduce eye strain and makes prolonged screen time more comfortable, and, let's be honest, it just looks way cooler. In this article, we'll look at how to easily add dark mode to your vue app using vueuse useColorMode composable.

Prerequisites

Before we begin, ensure you have the following:

  1. Vue 3 project set up
  2. Tailwind v4 set up

Setting Up Dark Mode in CSS

main.css

main.css

@import 'tailwindcss'; @custom-variant dark (&:where(.dark, .dark *)); :root { --background: #ffffff; --foreground: #11181c; } .dark { --background: #000000; --foreground: #ecedee; } @theme inline { --color-background: var(--background); --color-foreground: var(--foreground); } @layer base { body { background-color: var(--color-background); color: var(--color-foreground); } }

Install vueuse

Let's install @vueuse/core to have access to the useColorMode composable.

npm install @vueuse/core

Adding Theme Selection

Let's finally create buttons to update the theme between light, dark and auto(system).

App.vue

App.vue

<script setup lang="ts"> import { useColorMode } from '@vueuse/core' const { store: theme } = useColorMode({ initialValue: 'dark', // defaults to auto }) </script> <template> <div class="flex justify-center gap-x-4 items-center min-h-dvh"> <button @click="theme = 'light'">Light</button> <button @click="theme = 'dark'">Dark</button> <button @click="theme = 'auto'">System</button> </div> </template>

Conclusion

With just a few lines of code, we've implemented a dark mode feature in a Vue 3 app, complete with persistence using localStorage. Check out the repo for more ways to customize the useColorMode composable.

Enjoy!