【问题标题】:Adding a dark mode toggle to vuetify app v2.0 on nuxt.js在 nuxt.js 上添加暗模式切换以 vuetify app v2.0
【发布时间】:2020-04-19 07:53:09
【问题描述】:

我正在使用 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
        }
      }
    }
  },

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

【问题讨论】:

标签: javascript vue.js vuetify.js nuxt.js


【解决方案1】:

您可以在v-btn 上执行以下操作来操纵$vuetify.theme.dark

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

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

编辑:在本地存储中保存状态

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

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

在挂载后,您可以加载该状态

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

【讨论】:

  • 如何在localStorage中存储暗模式状态,并在应用启动时获取?
  • @FarshidRezaei 查看我的编辑。我就是这样做的
  • “mounted”函数放在哪里?哪个文件或组件?
  • 您希望对主题进行初始检查的任何位置。如果您有一个登录页面并且您希望它已经是黑暗的,那么它将是那个登录页面
【解决方案2】:

我自己修好了。转到 nuxt.config 并添加此代码。

buildModules: [
    [
      "@nuxtjs/vuetify",
      {
        treeShake: true,
        theme: {
          dark: true,
        }
      }
    ]
  ],

【讨论】:

  • 这是否提供了明暗模式之间的切换?我不明白如何..
【解决方案3】:

我发现为暗/亮模式添加开关按钮的好方法:

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

不需要其他任何东西。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-30
    • 2020-02-16
    • 2022-08-15
    • 2019-11-08
    • 1970-01-01
    • 2021-05-30
    • 2021-03-05
    • 2020-07-07
    相关资源
    最近更新 更多