How to implement a dark mode theme switcher in Vue
Aug 02, 2025 pm 12:15 PMCreate a theme toggle component, bind the isDarkMode state with checkboxes and call the toggleTheme function; 2. Check localStorage and system preferences for initializing the theme in onMounted; 3. Define the applyTheme function to apply the dark-mode class to the html element to switch styles; 4. Use CSS custom properties to define bright and dark variables, and override the default styles through the dark-mode class; 5. Introduce the ThemeSwitcher component into the main application template to display the toggle button; 6. Optionally listen to prefers-color-scheme changes to synchronize system themes. This solution uses Vue 3's Composition API, CSS classes and localStorage to achieve persistent and responsive theme switching capabilities, and ultimately completes efficient theme management without external libraries through simple HTML, CSS and JavaScript.
Implementing a dark mode theme switcher in Vue is straightforward and can be done using a combination of reactive state, CSS classes, and optionally persistent storage. Below is a step-by-step guide to achieve this in a Vue 3 application (Composition API), but the concept works similarly in Vue 2 with minor syntax changes.

? 1. Add a Theme Toggle Component
Create a simple toggle component (eg, ThemeSwitcher.vue
) that lets users switch between light and dark modes.
<!-- ThemeSwitcher.vue --> <template> <div class="theme-switcher"> <label class="switch"> <input type="checkbox" @change="toggleTheme" :checked="isDarkMode" /> <span class="slider"></span> </label> <span>{{ isDarkMode ? 'Dark Mode' : 'Light Mode' }}</span> </div> </template> <script setup> import { ref, onMounted } from 'vue'; // Reactive state for them const isDarkMode = ref(false); // Check user preference from localStorage or prefers-color-scheme onMounted(() => { const savedTheme = localStorage.getItem('theme'); const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches; isDarkMode.value = savedTheme === 'dark' || (savedTheme === null && prefersDark); applyTheme(isDarkMode.value); }); // Toggle theme and save preference function toggleTheme() { isDarkMode.value = !isDarkMode.value; applyTheme(isDarkMode.value); localStorage.setItem('theme', isDarkMode.value ? 'dark' : 'light'); } // Apply theme class to <html> element function applyTheme(dark) { document.documentElement.classList.toggle('dark-mode', dark); } </script> <style scoped> .theme-switcher { display: flex; align-items: center; gap: 8px; font-size: 14px; } /* The switch - the box around the slider */ .switch { position: relative; display: inline-block; width: 50px; height: 24px; } .switch input { opacity: 0; width: 0; height: 0; } /* Slider */ .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; transition: 0.4s; border-radius: 24px; } .slider:before { position: absolute; content: ''; height: 18px; width: 18px; left: 3px; bottom: 3px; background-color: white; transition: 0.4s; border-radius: 50%; } input:checked .slider { background-color: #4c56af; } input:checked .slider:before { transform: translateX(26px); } </style>
? 2. Define Dark Mode Styles in Your CSS
Use the .dark-mode
class on the <html>
element to override your default (light) styles.

/* In your main.css or App.vue styles */ :root { --bg-color: #ffffff; --text-color: #333333; } .dark-mode { --bg-color: #121212; --text-color: #f5f5f5; } body { background-color: var(--bg-color); color: var(--text-color); transition: background-color 0.3s ease, color 0.3s ease; }
You can extend this to buttons, cards, inputs, etc., by using the dark-mode
class context:
.card { background: #f8f9fa; border: 1px solid #dee2e6; } .dark-mode .card { background: #1e1e1e; border-color: #333; color: #f5f5f5; }
? 3. Mount the Theme Switcher in Your App
Include the ThemeSwitcher
component in your main layout or navbar.

<!-- App.vue or Layout.vue --> <template> <div id="app"> <ThemeSwitcher /> <router-view /> </div> </template> <script setup> import ThemeSwitcher from './components/ThemeSwitcher.vue'; </script>
? 4. Optional: Sync with System Preference
The onMounted
hook already checks prefers-color-scheme
, so new users get a system-appropriate default. This improves UX.
You could also listen for system theme changes:
// Inside onMounted, after initial setup const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)'); mediaQuery.addEventListener('change', (e) => { if (localStorage.getItem('theme') === null) { isDarkMode.value = e.matches; applyTheme(e.matches); } });
This ensures users who haven't manually chose a theme will follow system changes.
? Summary of Key Features
- ?? Toggle between light and dark themes
- ? Saves user preference in
localStorage
- ?? Respects system preference by default
- ? Uses CSS custom properties for easy themed
- ? Smooth transitions with CSS
That's it. You now have a working, persistent dark mode toggle in Vue. No external libraries needed — just Vue, a little CSS, and smart use of browser APIs.
Basically just wire up a checkbox, update a class on , and save the choice. Simple but effective.
The above is the detailed content of How to implement a dark mode theme switcher in Vue. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

To develop a complete Python Web application, follow these steps: 1. Choose the appropriate framework, such as Django or Flask. 2. Integrate databases and use ORMs such as SQLAlchemy. 3. Design the front-end and use Vue or React. 4. Perform the test, use pytest or unittest. 5. Deploy applications, use Docker and platforms such as Heroku or AWS. Through these steps, powerful and efficient web applications can be built.

Single-page applications (SPAs) can be built using Laravel and Vue.js. 1) Define API routing and controller in Laravel to process data logic. 2) Create a componentized front-end in Vue.js to realize user interface and data interaction. 3) Configure CORS and use axios for data interaction. 4) Use VueRouter to implement routing management and improve user experience.

ToimplementdarkmodeinCSSeffectively,useCSSvariablesforthemecolors,detectsystempreferenceswithprefers-color-scheme,addamanualtogglebutton,andhandleimagesandbackgroundsthoughtfully.1.DefineCSSvariablesforlightanddarkthemestomanagecolorsefficiently.2.Us

The core of the front-end routing system is to map URLs to components. VueRouter and ReactRouter realize refresh-free page switching by listening for URL changes and loading corresponding components. The configuration methods include: 1. Nested routing, allowing the nested child components in the parent component; 2. Dynamic routing, loading different components according to URL parameters; 3. Route guard, performing logic such as permission checks before and after route switching.

ReactivitytransforminVue3aimedtosimplifyhandlingreactivedatabyautomaticallytrackingandmanagingreactivitywithoutrequiringmanualref()or.valueusage.Itsoughttoreduceboilerplateandimprovecodereadabilitybytreatingvariableslikeletandconstasautomaticallyreac

The core differences between Vue.js and React in component development are: 1) Vue.js uses template syntax and option API, while React uses JSX and functional components; 2) Vue.js uses responsive systems, React uses immutable data and virtual DOM; 3) Vue.js provides multiple life cycle hooks, while React uses more useEffect hooks.

InternationalizationandlocalizationinVueappsareprimarilyhandledusingtheVueI18nplugin.1.Installvue-i18nvianpmoryarn.2.CreatelocaleJSONfiles(e.g.,en.json,es.json)fortranslationmessages.3.Setupthei18ninstanceinmain.jswithlocaleconfigurationandmessagefil

When Vue.js handles array updates, the view is not updated because Object.defineProperty cannot directly listen to array changes. Solutions include: 1. Use the Vue.set method to modify the array index; 2. Reassign the entire array; 3. Use the rewritten mutation method of Vue to operate the array.
