首页 > 解决方案 > Vuetify 在明暗主题之间切换(使用 vuex)

问题描述

所以在我的 Vue 项目中,我基本上有两个页面/组件,它们将根据 URL 使用 vue-router 来显示。我可以通过一个按钮在这些页面/组件之间切换。

我也在使用 VueX 来管理一些数据。

现在,我在其中一个组件中添加了一个开关,用于在 Vuetify 的深色和浅色主题之间切换。

在此组件的模板中,我执行以下操作:

    <v-switch
      label="Toggle dark them"
      @change="toggleDarkTheme()"
    ></v-switch>

在被调用的函数中,我这样做:

    toggleDarkTheme() {
          this.$vuetify.theme.dark = !this.$vuetify.theme.dark;
          console.log(this.$vuetify.theme.dark);
    },

在 app.vue 中,我包含了<v-app dark>和在我的 main.js 中,我有以下内容:

    Vue.use(Vuetify);
    const vuetify = new Vuetify({
      theme: {
        // dark: true,
        themes: {
          light: {
            primary: colors.purple,
            secondary: colors.grey.darken1,
            accent: colors.shades.black,
            error: colors.red.accent3,
            background: colors.indigo.lighten5, 
          },
          dark: {
            primary: colors.blue.lighten3,
            background: colors.indigo.base,
          },
        },
      },
    });
    
    Vue.config.productionTip = false;
    
    new Vue({
      router,
      store,
      vuetify,
      render: (h) => h(App),
    }).$mount('#app');

所以我现在的问题是,当我点击开关时,这个组件中的主题确实从浅色模式切换到了深色模式。浅色模式是默认设置,当我单击一次开关时,我会得到深色主题。但是,当我单击按钮切换到另一个 URL 时,将使用浅色主题。如何正确实现此功能?

提前致谢!

标签: vue.jsswitch-statementthemesvuexvuetify.js

解决方案


您应该有一个名为 的 JavaScript 类vuetify.js,在您的情况下应该如下所示。

import Vue from "vue";
import Vuetify from "vuetify/lib";

Vue.use(Vuetify);

export default new Vuetify({
  theme: {
    themes: {
      light: {
        primary: colors.purple,
        secondary: colors.grey.darken1,
        accent: colors.shades.black,
        error: colors.red.accent3,
        background: colors.indigo.lighten5
      },
      dark: {
        primary: colors.blue.lighten3,
        background: colors.indigo.base
      }
    }
  }
});

你的开关应该可以工作,但以防万一,试试我在你的组件中制作的这个按钮。

    <div>
      <v-tooltip v-if="!$vuetify.theme.dark" bottom>
        <template v-slot:activator="{ on }">
          <v-btn v-on="on" color="info" small fab @click="darkMode">
            <v-icon class="mr-1">mdi-moon-waxing-crescent</v-icon>
          </v-btn>
        </template>
        <span>Dark Mode On</span>
      </v-tooltip>

      <v-tooltip v-else bottom>
        <template v-slot:activator="{ on }">
          <v-btn v-on="on" color="info" small fab @click="darkMode">
            <v-icon color="yellow">mdi-white-balance-sunny</v-icon>
          </v-btn>
        </template>
        <span>Dark Mode Off</span>
      </v-tooltip>
    </div>

Button 在您的<script>

darkMode() {
      this.$vuetify.theme.dark = !this.$vuetify.theme.dark;
    }

推荐阅读