亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
? 2. Define Dark Mode Styles in Your CSS
? 3. Mount the Theme Switcher in Your App
? 4. Optional: Sync with System Preference
? Summary of Key Features
Home Web Front-end Vue.js How to implement a dark mode theme switcher in Vue

How to implement a dark mode theme switcher in Vue

Aug 02, 2025 pm 12:15 PM
vue Dark Mode

Create 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.

How to implement a dark mode theme switcher in Vue

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.

How to implement a dark mode theme switcher in Vue

? 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 ? &#39;Dark Mode&#39; : &#39;Light Mode&#39; }}</span>
  </div>
</template>

<script setup>
import { ref, onMounted } from &#39;vue&#39;;

// Reactive state for them
const isDarkMode = ref(false);

// Check user preference from localStorage or prefers-color-scheme
onMounted(() => {
  const savedTheme = localStorage.getItem(&#39;theme&#39;);
  const prefersDark = window.matchMedia(&#39;(prefers-color-scheme: dark)&#39;).matches;

  isDarkMode.value = savedTheme === &#39;dark&#39; || (savedTheme === null && prefersDark);
  applyTheme(isDarkMode.value);
});

// Toggle theme and save preference
function toggleTheme() {
  isDarkMode.value = !isDarkMode.value;
  applyTheme(isDarkMode.value);
  localStorage.setItem(&#39;theme&#39;, isDarkMode.value ? &#39;dark&#39; : &#39;light&#39;);
}

// Apply theme class to <html> element
function applyTheme(dark) {
  document.documentElement.classList.toggle(&#39;dark-mode&#39;, 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: &#39;&#39;;
  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.

How to implement a dark mode theme switcher in Vue
 /* 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.

How to implement a dark mode theme switcher in Vue
 <!-- App.vue or Layout.vue -->
<template>
  <div id="app">
    <ThemeSwitcher />
    <router-view />
  </div>
</template>

<script setup>
import ThemeSwitcher from &#39;./components/ThemeSwitcher.vue&#39;;
</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(&#39;(prefers-color-scheme: dark)&#39;);
mediaQuery.addEventListener(&#39;change&#39;, (e) => {
  if (localStorage.getItem(&#39;theme&#39;) === 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to develop a complete Python Web application? How to develop a complete Python Web application? May 23, 2025 pm 10:39 PM

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.

Laravel Vue.js single page application (SPA) tutorial Laravel Vue.js single page application (SPA) tutorial May 15, 2025 pm 09:54 PM

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.

How can CSS be used to implement dark mode theming on a website? How can CSS be used to implement dark mode theming on a website? Jun 19, 2025 am 12:51 AM

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

How to work and configuration of front-end routing (Vue Router, React Router)? How to work and configuration of front-end routing (Vue Router, React Router)? May 20, 2025 pm 07:18 PM

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.

What is the significance of Vue's reactivity transform (experimental, then removed) and its goals? What is the significance of Vue's reactivity transform (experimental, then removed) and its goals? Jun 20, 2025 am 01:01 AM

ReactivitytransforminVue3aimedtosimplifyhandlingreactivedatabyautomaticallytrackingandmanagingreactivitywithoutrequiringmanualref()or.valueusage.Itsoughttoreduceboilerplateandimprovecodereadabilitybytreatingvariableslikeletandconstasautomaticallyreac

What are the core differences between Vue.js and React in componentized development? What are the core differences between Vue.js and React in componentized development? May 21, 2025 pm 08:39 PM

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.

How can internationalization (i18n) and localization (l10n) be implemented in a Vue application? How can internationalization (i18n) and localization (l10n) be implemented in a Vue application? Jun 20, 2025 am 01:00 AM

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

Vue responsive principle and solution to not trigger view updates when array updates? Vue responsive principle and solution to not trigger view updates when array updates? May 20, 2025 pm 06:54 PM

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.

See all articles