在 nuxt.js 上为 vuetify app v2.0 添加暗模式切换

Fay*_*yaz 2 javascript vue.js nuxt.js vuetify.js

我正在使用 nuxt.js vuetify 模板,nuxt.config.js 已经有一个对象(下面提到),它定义了应用程序的暗模式。

  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
        }
      }
    }
  },
Run Code Online (Sandbox Code Playgroud)

如何将其添加为功能,作为从浅色版本切换到深色版本的按钮?Vuetify 有主题定制的文档,但没有正确的方法来解释如何在应用程序中执行此操作。

dis*_*lor 6

您可以对 a 执行以下v-btn操作来操作$vuetify.theme.dark.

<v-btn @click="$vuetify.theme.dark=!$vuetify.theme.dark">Toggle Theme</v-btn>
Run Code Online (Sandbox Code Playgroud)

这将在明暗主题之间切换。该设置在文档的标题“ Light and Dark ”中进行了描述,尽管我承认很容易错过。

编辑:在 localStorage 中保存状态

创建一个方法并调用它@click。

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

并在安装后,您可以加载该状态

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