Implementing a night mode switch in a Vuetify application version 2.0 built on Nuxt.js

I have integrated the nuxt.js vuetify template, and within the nuxt.config.js file, there is an object (shown below) that sets up the dark mode for the application.

  vuetify: {
    customVariables: ['~/assets/variables.scss'],
    theme: {
      dark: true,
      themes: {
        dark: {
          primary: colors.blue.darken2,
          accent: colors.grey.darken3,
          secondary: colors.amber.darken3,
          info: colors.teal.lighten1,
          warning: colors.amber.base,
          error: colors.deepOrange.accent4,
          success: colors.green.accent3
        }
      }
    }
  },

I am trying to implement a feature where users can toggle between the light and dark versions. While Vuetify provides documentation on theme customization, it lacks a clear explanation on how to achieve this functionality within the app.

Answer №1

If you want to control the $vuetify.theme.dark property using a v-btn, you can add the following code.

<v-btn @click="$vuetify.theme.dark=!$vuetify.theme.dark">Toggle Theme</v-btn>

This will switch between the light and dark themes. You can find more information about this setting under the title "Light and Dark" in the documentation, although it may be easy to overlook.

Edit: Saving the state in localStorage

Create a method and invoke it on @click.

toggleTheme() {
   this.$vuetify.theme.dark=!this.$vuetify.theme.dark;
   localStorage.setItem("useDarkTheme", this.$vuetify.theme.dark.toString())
}

Upon mounting the component, load the saved state from localStorage

mounted() {
  const theme = localStorage.getItem("useDarkTheme");
    if (theme) {
      if (theme == "true") {
        this.$vuetify.theme.dark = true;
      } else this.$vuetify.theme.dark = false;
    }
}

Answer №2

Simple and efficient technique discovered to incorporate a toggle button for switching between dark and light mode:

<v-btn
  icon
  :color="$vuetify.theme.dark ? 'yellow' : 'dark'"
  @click="$vuetify.theme.dark = !$vuetify.theme.dark"
>

No additional steps required.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using JavaScript to identify the unlock screen on a website

I've been searching everywhere for a solution to my issue, but I haven't had any luck with Google or other websites. I'm currently working on creating a mobile website and I need assistance with redirecting users to the homepage in such a w ...

Accessing the selected value from a dropdown list filled with data from a PHP array in HTML

My HTML and PHP code consists of a select dropdown that looks like this: <select name="category" id="_category" class="_cateogry" onchange="submitTheForm() > option value="">Please select</option> <?php foreach ($categories as $cont ...

Navigating to a URL within an array object using Vue.js 3

I am working with an array of items that contain the title, icon, and URL for each item. My goal is to redirect the user to the specified URL when they click on an item. How can I achieve this using markup? state: { navigation: [ { title: "H ...

Adding the AJAX response to the specified element's ID

I'm having trouble inserting radio buttons into a <div> on my page using an AJAX response. The code I have looks like this: // AJAX form for updating tests after category selection $('#categories').change(function(){ category_id ...

an explanation of the date format used in Google Calendar

I'm attempting to incorporate Google Calendar into my website using the following URL: <a href="https://calendar.google.com/calendar/render? action=TEMPLATE& text={{ticket.subject}}& dates=20170127T210000Z/20170127T220000Z& ...

What is the best way to swap out an element in vue.js?

Here is the code I am working with: window.onload = (event) => { new Vue({ el: "#test", mounted: function() { this.fetch(); setInterval(this.fetch, 60000); ...

How can I modify the material and color of the result in Three.js CSG?

Upon creating a union of two meshes, I want to apply MeshLambertMaterial specifically on the object named 'result': var lathe = new THREE.Mesh(latheGeometry); var cube_bsp = new ThreeBSP( lathe ); var box = new THREE.BoxGeometry( 2,30,3); var ...

Why is my backend sending two Objects in the http response instead of just one?

When I receive data from my Django backend, sometimes instead of one object I get two objects within the HTTP response. This inconsistency is puzzling because it occurs intermittently - at times there's only one object, while other times there are two ...

Comparison of Grant and Passport.js: Which One to Choose?

Are you unsure about the distinctions between Grant and Passport.js? How do you decide when to utilize Grant over passport.js, and vice versa? If your goal is to create a social media platform that tracks user activities and posts them on a news feed, whi ...

Unable to assign headers once they have already been sent to the recipient - a Node.js error

Encountering an error message stating "Cannot set headers after they are sent to the client." I've researched and it seems like multiple callbacks may be causing this issue. However, I'm struggling to find a solution. Any assistance in resolving ...

using an array as a parameter in an axios request

For the request I'm working on using Axios, I'm aiming to send an array like this [1,2,3,4]. This array will be used for a selection query in my backend. My question is whether it's better to use a GET or POST request for this purpose, and w ...

What is the best way to use lodash to group objects that contain nested objects?

Currently utilizing Typescript in conjunction with Lodash! Upon retrieving data from the database, here is the resulting output: [ { "unitPrice": 0.01, "code": "92365524", "description": "Broto gr ...

Is it possible to execute appendChild in the context of JS-DOM-creation?

Hey there, I'm a newbie trying my hand at DOM creation. I've encountered a strange issue with appendChild - the first and second tries work fine, but I'm completely stuck on the third attempt. Here's my HTML: <html> <head> ...

Exploring the output files of C programs using JavaScript

I have been attempting to link two programs I created. One is a C program that generates files on my local disk, and the other is a web program designed to display the contents of these files on screen by accessing them from my disk. Despite trying vario ...

At times, the map may only be visible in the top left corner of its designated container

Currently, I am integrating the Google Maps API v3 for JavaScript into my project. However, I am facing an issue where the map only appears in the upper left corner under certain circumstances. To visualize this problem, you can visit this link and click ...

Encountering a POST 504 error while attempting to proxy an Angular application to a Node server

error message: Failed to connect to http://localhost:4200/api/user/login with a 504 Gateway Timeout error. Encountered this issue while attempting to set up a login feature in my Angular application and establish communication with the Express backend. Th ...

Utilizing JavaScript for Formatting and Comparing Dates

Here, I would like to compare the current date with a user-inputted date. <script type="text/javascript"> $(document).ready(function(){ $("#date").change(function(){ var realDate = new Date(); var startDate = new ...

Updating content on a webpage via AJAX request without altering the original source code

Within the body of our document, referred to as "form.php," we have the following components: At the head section, there is a JavaScript code block: <script> function showUser(str) { if (str == "") { document.getElementById("txtHint").i ...

Tips for displaying JSON data by formatting it into separate div elements for the result object

Having recently started using the Amadeus REST API, I've been making AJAX calls to retrieve data. However, I'm facing a challenge when it comes to representing this data in a specific format and looping through it effectively. function showdataf ...

How can I create a JSON output from my MySQL database that includes the total count of records per day for a Task entry?

I am looking to implement the JavaScript library called Cal-Heatmap (https://kamisama.github.io/cal-heatmap/) to create an Event style heatmap similar to GitHub's. The objective is to visualize the number of actions taken on each Task record in my Pr ...