JAVASCRIPT

Vue 3 Dark Mode Toggle with Local Storage Persistence

Implement a persistent dark mode toggle in Vue 3 using reactive state and browser local storage. This snippet saves user preference across sessions.

// src/App.vue
<template>
  <div :class="{ 'dark-mode': isDarkMode }">
    <h1>Welcome to My App</h1>
    <p>This is some content.</p>
    <button @click="toggleDarkMode">
      Toggle Dark Mode ({{ isDarkMode ? 'On' : 'Off' }})
    </button>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';

const isDarkMode = ref(false); // Default to light mode

const toggleDarkMode = () => {
  isDarkMode.value = !isDarkMode.value;
};

// On component mount, check local storage for user preference
onMounted(() => {
  const savedMode = localStorage.getItem('darkMode');
  if (savedMode !== null) {
    isDarkMode.value = JSON.parse(savedMode);
  } else {
    // Optional: detect system preference
    isDarkMode.value = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
  }
});

// Watch for changes in isDarkMode and update local storage
watch(isDarkMode, (newValue) => {
  localStorage.setItem('darkMode', JSON.stringify(newValue));
  // Apply class to body or root element
  document.documentElement.classList.toggle('dark-mode', newValue);
});
</script>

<style>
/* Base styles */
body {
  margin: 0;
  font-family: sans-serif;
  transition: background-color 0.3s ease, color 0.3s ease;
}

/* Light mode defaults */
body {
  background-color: #f0f2f5;
  color: #333;
}

/* Dark mode styles */
body.dark-mode {
  background-color: #2c2c2c;
  color: #f0f0f0;
}

/* Apply dark mode to content within the app (if not applied to body) */
.dark-mode { /* This class is applied to the root div in App.vue */
  /* If body is already styled, this might not be needed or can override */
  /* For demonstration, let's assume body.dark-mode is already set. */
}
</style>
How it works: This snippet demonstrates how to implement a dark mode toggle in a Vue 3 application with persistence using local storage. It uses `ref` for reactive state, `onMounted` to retrieve the saved preference, and `watch` to store changes. The `dark-mode` class is dynamically applied to the `body` (or root element), enabling CSS to switch between light and dark themes and ensuring the user's preference is remembered across sessions.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs