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

目錄
? 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
首頁 web前端 Vue.js 如何在VUE中實(shí)現(xiàn)暗模式主題切換器

如何在VUE中實(shí)現(xiàn)暗模式主題切換器

Aug 02, 2025 pm 12:15 PM
vue 暗黑模式

創(chuàng)建一個(gè)主題切換組件,使用復(fù)選框綁定 isDarkMode 狀態(tài)并調(diào)用 toggleTheme 函數(shù);2. 在 onMounted 中檢查 localStorage 和系統(tǒng)偏好設(shè)置初始化主題;3. 定義 applyTheme 函數(shù)將 dark-mode 類應(yīng)用到 html 元素以切換樣式;4. 使用 CSS 自定義屬性定義亮色和暗色變量,并通過 dark-mode 類覆蓋默認(rèn)樣式;5. 將 ThemeSwitcher 組件引入主應(yīng)用模板中以顯示切換按鈕;6. 可選地監(jiān)聽 prefers-color-scheme 變化以同步系統(tǒng)主題。該方案利用 Vue 3 的 Composition API、CSS 類和 localStorage 實(shí)現(xiàn)了持久化且響應(yīng)系統(tǒng)偏好的主題切換功能,最終通過簡單的 HTML、CSS 和 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 (e.g., 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 theme
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.

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 './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 chosen 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 theming
  • ? 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.

以上是如何在VUE中實(shí)現(xiàn)暗模式主題切換器的詳細(xì)內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻(xiàn),版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動(dòng)的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機(jī)

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強(qiáng)大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級(jí)代碼編輯軟件(SublimeText3)

熱門話題

Laravel 教程
1597
29
PHP教程
1488
72
怎樣開發(fā)一個(gè)完整的PythonWeb應(yīng)用程序? 怎樣開發(fā)一個(gè)完整的PythonWeb應(yīng)用程序? May 23, 2025 pm 10:39 PM

要開發(fā)一個(gè)完整的PythonWeb應(yīng)用程序,應(yīng)遵循以下步驟:1.選擇合適的框架,如Django或Flask。2.集成數(shù)據(jù)庫,使用ORM如SQLAlchemy。3.設(shè)計(jì)前端,使用Vue或React。4.進(jìn)行測試,使用pytest或unittest。5.部署應(yīng)用,使用Docker和平臺(tái)如Heroku或AWS。通過這些步驟,可以構(gòu)建出功能強(qiáng)大且高效的Web應(yīng)用。

Laravel   Vue.js 開發(fā)單頁面應(yīng)用(SPA)教程 Laravel Vue.js 開發(fā)單頁面應(yīng)用(SPA)教程 May 15, 2025 pm 09:54 PM

使用Laravel和Vue.js可以構(gòu)建單頁面應(yīng)用(SPA)。1)在Laravel中定義API路由和控制器,處理數(shù)據(jù)邏輯。2)在Vue.js中創(chuàng)建組件化前端,實(shí)現(xiàn)用戶界面和數(shù)據(jù)交互。3)配置CORS和使用axios進(jìn)行數(shù)據(jù)交互。4)利用VueRouter實(shí)現(xiàn)路由管理,提升用戶體驗(yàn)。

如何使用CSS在網(wǎng)站上實(shí)現(xiàn)黑模式主題? 如何使用CSS在網(wǎng)站上實(shí)現(xiàn)黑模式主題? Jun 19, 2025 am 12:51 AM

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

前端路由(Vue Router、React Router)的工作原理及配置方法? 前端路由(Vue Router、React Router)的工作原理及配置方法? May 20, 2025 pm 07:18 PM

前端路由系統(tǒng)的核心是將URL映射到組件,VueRouter和ReactRouter通過監(jiān)聽URL變化并加載相應(yīng)組件實(shí)現(xiàn)無刷新頁面切換。配置方法包括:1.嵌套路由,允許在父組件中嵌套子組件;2.動(dòng)態(tài)路由,根據(jù)URL參數(shù)加載不同組件;3.路由守衛(wèi),在路由切換前后執(zhí)行邏輯如權(quán)限檢查。

Vue的反應(yīng)性轉(zhuǎn)換(實(shí)驗(yàn),然后被刪除)的意義是什么? Vue的反應(yīng)性轉(zhuǎn)換(實(shí)驗(yàn),然后被刪除)的意義是什么? Jun 20, 2025 am 01:01 AM

ReactivitytransforminVue3aimedtosimplifyhandlingreactivedatabyautomaticallytrackingandmanagingreactivitywithoutrequiringmanualref()or.valueusage.Itsoughttoreduceboilerplateandimprovecodereadabilitybytreatingvariableslikeletandconstasautomaticallyreac

Vue.js 與 React 在組件化開發(fā)中的核心差異是什么? Vue.js 與 React 在組件化開發(fā)中的核心差異是什么? May 21, 2025 pm 08:39 PM

Vue.js和React在組件化開發(fā)中的核心差異在于:1)Vue.js使用模板語法和選項(xiàng)式API,而React使用JSX和函數(shù)式組件;2)Vue.js采用響應(yīng)式系統(tǒng),React則使用不可變數(shù)據(jù)和虛擬DOM;3)Vue.js提供多個(gè)生命周期鉤子,React則更多使用useEffect鉤子。

如何在VUE應(yīng)用程序中實(shí)施國際化(I18N)和本地化(L10N)? 如何在VUE應(yīng)用程序中實(shí)施國際化(I18N)和本地化(L10N)? Jun 20, 2025 am 01:00 AM

國際化和傾斜度invueAppsareprimandermedusingthevuei18nplugin.1.installvue-i18nvianpmoryarn.2.createlo calejsonfiles(例如,en.json,es.json)fortranslationMessages.3.setupthei18ninstanceinmain.jswithlocaleconfigurationandmessagefil

Vue 響應(yīng)式原理及在數(shù)組更新時(shí)不觸發(fā)視圖更新的解決方案? Vue 響應(yīng)式原理及在數(shù)組更新時(shí)不觸發(fā)視圖更新的解決方案? May 20, 2025 pm 06:54 PM

Vue.js處理數(shù)組更新時(shí),視圖未更新是因?yàn)镺bject.defineProperty無法直接監(jiān)聽到數(shù)組變化。解決方法包括:1.使用Vue.set方法修改數(shù)組索引;2.重新賦值整個(gè)數(shù)組;3.使用Vue重寫過的變異方法操作數(shù)組。

See all articles