Table of Contents
Basic Structure: Use data attributes to control topics
Persistence settings: Use localStorage to remember user preferences
Style processing: Control topics with CSS class names
Optional Advanced: Use Vuex to manage global theme status
Home Web Front-end Vue.js Example of a dark mode toggle in a Vue app

Example of a dark mode toggle in a Vue app

Jul 26, 2025 am 12:48 AM
vue Dark Mode

The core steps in implementing the dark mode switching function in Vue applications are as follows: 1. Use data attributes to manage theme status and implement style switching by binding class names; 2. Use localStorage to persist user preferences so that settings still take effect after page refresh; 3. Define dark theme styles in CSS by adding dark classes to html or body; 4. It is recommended to use Vuex to manage global theme status in large projects to improve maintainability. These steps correspond to advanced applications of basic implementation, state persistence, style control and state management, ensuring that dark mode functions are complete and experience is consistent.

Example of a dark mode toggle in a Vue app

Implementing a dark mode switching function is actually not complicated in Vue applications. The key is how to elegantly manage theme state and style switching. Here is a simple dark mode toggle example covering core logic and common practices.

Example of a dark mode toggle in a Vue app

Basic Structure: Use data attributes to control topics

The most direct way is to maintain a darkMode 's boolean value in the component's data :

 <template>
  <div :class="{ &#39;dark&#39;: darkMode }">
    <button @click="toggleDarkMode">
      {{ darkMode ? &#39;Light Mode&#39; : &#39;Dark Mode&#39; }}
    </button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      darkMode: false
    }
  },
  methods: {
    toggleDarkMode() {
      this.darkMode = !this.darkMode
    }
  }
}
</script>

The advantage of writing this way is that it is simple and intuitive, suitable for small projects or rapid prototypes. But if you want the user to remember the topic you selected last time after refreshing the page, you need to persistent storage.

Example of a dark mode toggle in a Vue app

Persistence settings: Use localStorage to remember user preferences

You can combine localStorage to save the user's theme selection:

 data() {
  return {
    darkMode: localStorage.getItem(&#39;darkMode&#39;) === &#39;true&#39;
  }
},
methods: {
  toggleDarkMode() {
    this.darkMode = !this.darkMode
    localStorage.setItem(&#39;darkMode&#39;, this.darkMode)
  }
}

In this way, even if the user refreshes the page, he can maintain the previously set theme. This method is more common and easy to expand.

Example of a dark mode toggle in a Vue app

Style processing: Control topics with CSS class names

Usually we will control the overall style by adding dark classes to <html> or <body> :

 <template>
  <html :class="{ dark: darkMode }">
    <!-- Page content-->
  </html>
</template>

Then use the .dark class in CSS to define dark styles, for example:

 body {
  background: #ffff;
  color: #333;
}

.dark body {
  background: #121212;
  color: #e6e6e6;
}

If you use Tailwind CSS or other tool class frameworks, you can also dynamically apply the styles based on the class name.


Optional Advanced: Use Vuex to manage global theme status

If your application is large, it is recommended to put darkMode into the Vuex store to manage it uniformly:

 // store.js
state: {
  darkMode: localStorage.getItem(&#39;darkMode&#39;) === &#39;true&#39;
},
mutations: {
  setDarkMode(state, value) {
    state.darkMode = value
    localStorage.setItem(&#39;darkMode&#39;, value)
  }
}

Then in the component call via mapMutations:

 import { mapMutations } from &#39;vuex&#39;

export default {
  methods: {
    ...mapMutations([&#39;setDarkMode&#39;]),
    toggleDarkMode() {
      this.setDarkMode(!this.darkMode)
    }
  }
}

This allows multiple components to share the theme state and improve maintainability.


Basically that's it. There are many ways to implement dark mode toggle, the key is to choose a method that suits your project scale and needs. It is not complicated, but paying attention to state management and style adaptation in details is the key.

The above is the detailed content of Example of a dark mode toggle in a Vue app. 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)

Hot Topics

PHP Tutorial
1504
276
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

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

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

What is server side rendering SSR in Vue? What is server side rendering SSR in Vue? Jun 25, 2025 am 12:49 AM

Server-siderendering(SSR)inVueimprovesperformanceandSEObygeneratingHTMLontheserver.1.TheserverrunsVueappcodeandgeneratesHTMLbasedonthecurrentroute.2.ThatHTMLissenttothebrowserimmediately.3.Vuehydratesthepage,attachingeventlistenerstomakeitinteractive

How to implement transitions and animations in Vue? How to implement transitions and animations in Vue? Jun 24, 2025 pm 02:17 PM

ToaddtransitionsandanimationsinVue,usebuilt-incomponentslikeand,applyCSSclasses,leveragetransitionhooksforcontrol,andoptimizeperformance.1.WrapelementswithandapplyCSStransitionclasseslikev-enter-activeforbasicfadeorslideeffects.2.Useforanimatingdynam

How to build a component library with Vue? How to build a component library with Vue? Jul 10, 2025 pm 12:14 PM

Building a Vue component library requires designing the structure around the business scenario and following the complete process of development, testing and release. 1. The structural design should be classified according to functional modules, including basic components, layout components and business components; 2. Use SCSS or CSS variables to unify the theme and style; 3. Unify the naming specifications and introduce ESLint and Prettier to ensure the consistent code style; 4. Display the usage of components on the supporting document site; 5. Use Vite and other tools to package as NPM packages and configure rollupOptions; 6. Follow the semver specification to manage versions and changelogs when publishing.

How to use PHP to develop a Q&A community platform Detailed explanation of PHP interactive community monetization model How to use PHP to develop a Q&A community platform Detailed explanation of PHP interactive community monetization model Jul 23, 2025 pm 07:21 PM

1. The first choice for the Laravel MySQL Vue/React combination in the PHP development question and answer community is the first choice for Laravel MySQL Vue/React combination, due to its maturity in the ecosystem and high development efficiency; 2. High performance requires dependence on cache (Redis), database optimization, CDN and asynchronous queues; 3. Security must be done with input filtering, CSRF protection, HTTPS, password encryption and permission control; 4. Money optional advertising, member subscription, rewards, commissions, knowledge payment and other models, the core is to match community tone and user needs.

What is the purpose of the nextTick function in Vue, and when is it necessary? What is the purpose of the nextTick function in Vue, and when is it necessary? Jun 19, 2025 am 12:58 AM

nextTick is used in Vue to execute code after DOM update. When the data changes, Vue will not update the DOM immediately, but will put it in the queue and process it in the next event loop "tick". Therefore, if you need to access or operate the updated DOM, nextTick should be used; common scenarios include: accessing the updated DOM content, collaborating with third-party libraries that rely on the DOM state, and calculating based on the element size; its usage includes calling this.$nextTick as a component method, using it alone after import, and combining async/await; precautions include: avoiding excessive use, in most cases, no manual triggering is required, and a nextTick can capture multiple updates at a time.

See all articles