admin管理员组

文章数量:1334910

I am using nuxt.js vuetify template, nuxt.config.js already has a object (mentioned below) which defines dark mode for the app.

  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
        }
      }
    }
  },

How do I add this as a feature, as a button to toggle from light version to dark? Vuetify has documentation for theme customization, but no proper way which explains how to do this within the app.

I am using nuxt.js vuetify template, nuxt.config.js already has a object (mentioned below) which defines dark mode for the app.

  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
        }
      }
    }
  },

How do I add this as a feature, as a button to toggle from light version to dark? Vuetify has documentation for theme customization, but no proper way which explains how to do this within the app.

Share Improve this question edited Dec 30, 2019 at 15:29 Fayaz asked Dec 30, 2019 at 15:16 FayazFayaz 471 silver badge7 bronze badges 1
  • Also, check out this example for reference: vuetifyjs./en/features/theme/#example – Nebulosar Commented Aug 13, 2021 at 8:30
Add a ment  | 

2 Answers 2

Reset to default 8

You could do the following on a v-btn to manipulate $vuetify.theme.dark.

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

This will toggle between the light and dark theme. The setting is described at the title "Light and Dark" in the documentation, though I admit it is easy to miss.

Edit: Save state in localStorage

Create a method and call it @click.

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

and on mounted you could then load that state

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

Nice and fastest way I found to add a switch button for dark/light mode:

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

Nothing else needed.

本文标签: javascriptAdding a dark mode toggle to vuetify app v20 on nuxtjsStack Overflow