Example of a dark mode toggle in a Vue app
Jul 26, 2025 am 12:48 AMThe 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.
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.

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="{ 'dark': darkMode }"> <button @click="toggleDarkMode"> {{ darkMode ? 'Light Mode' : 'Dark Mode' }} </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.

Persistence settings: Use localStorage to remember user preferences
You can combine localStorage
to save the user's theme selection:
data() { return { darkMode: localStorage.getItem('darkMode') === 'true' } }, methods: { toggleDarkMode() { this.darkMode = !this.darkMode localStorage.setItem('darkMode', 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.

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('darkMode') === 'true' }, mutations: { setDarkMode(state, value) { state.darkMode = value localStorage.setItem('darkMode', value) } }
Then in the component call via mapMutations:
import { mapMutations } from 'vuex' export default { methods: { ...mapMutations(['setDarkMode']), 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!

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.

How to configure VSCode to write Vue: Install the Vue CLI and VSCode Vue plug-in. Create a Vue project. Set syntax highlighting, linting, automatic formatting, and code snippets. Install ESLint and Prettier to enhance code quality. Integrated Git (optional). After the configuration is complete, VSCode is ready for Vue development.

It is not recommended to directly modify the native code when separating WordPress front and back ends, and it is more suitable for "improved separation". Use the REST API to obtain data and build a user interface using the front-end framework. Identify which functions are called through the API, which are retained on the backend, and which can be cancelled. The Headless WordPress mode allows for a more thorough separation, but it is more cost-effective and difficult to develop. Pay attention to security and performance, optimize API response speed and cache, and optimize WordPress itself. Gradually migrate functions and use version control tools to manage code.

Running a Vue project in VSCode requires the following steps: 1. Install the Vue CLI; 2. Create a Vue project; 3. Switch to the project directory; 4. Install project dependencies; 5. Run the development server; 6. Open the browser to visit http://localhost:8080.

How to push video streams from Hikvision camera SDK to front-end Vue project? During the development process, you often encounter videos that need to be captured by the camera to be circulated...

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.
