How to Implement Dark Mode in a Vue.js App

 How to Implement Dark Mode in a Vue.js App


Overview: In this blog post, we'll explore how to add a dark mode feature to a Vue.js app. We'll cover the basics of using CSS variables to define color themes, how to toggle between light and dark modes using Vuex, and how to persist the user's preference using local storage.


Code Snippet:


html


<template>

  <div class="app" :class="{ 'dark-mode': isDarkMode }">

    <header>

      <h1>{{ title }}</h1>

      <button @click="toggleDarkMode">{{ isDarkMode ? 'Light Mode' : 'Dark Mode' }}</button>

    </header>

    <main>

      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>

    </main>

  </div>

</template>


<script>

import { mapGetters, mapMutations } from 'vuex';


export default {

  computed: {

    ...mapGetters(['isDarkMode']),

    title() {

      return this.isDarkMode ? 'My App (Dark Mode)' : 'My App (Light Mode)';

    },

  },

  methods: {

    ...mapMutations(['toggleDarkMode']),

  },

};

</script>


<style>

:root {

  --background-color: #fff;

  --text-color: #333;

}


.dark-mode {

  --background-color: #333;

  --text-color: #fff;

}


body {

  background-color: var(--background-color);

  color: var(--text-color);

}

</style>

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...