ブログ一覧に戻る

Nuxt+Vuetifyにダークモード切り替えボタンを実装してみた。

JavaScriptNuxtVueVuetify

みなさんこんにちは!
イザナギです!


vuetify: {
    customVariables: ['~/assets/variables.scss'],
    theme: {
      dark: false,
      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
        },
        light: {
          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
        },
        options: {
          customProperties: true
        }
      }
    }
  },


export const state = () => ({
  theme: false,
});

export const mutations = {
  theme(state, theme) {
    state.theme = theme
  }
}

export const actions = {
  theme({
    commit
  }, theme) {
    commit('theme', theme)
  }
}


<templete>
<v-switch v-model="theme"></v-switch>
</templete>
<script>
export default {
  data() {
    return {
      theme: this.$store.state.theme,
    }
  },
  watch: {
    theme() {
      this.$store.dispatch("theme", this.theme);
      this.$vuetify.theme.dark = this.theme;
    },
  },
};
</script>

「$vuetify.theme.dark 」にtrueを入れるとダークテーマ、falseを入れるとライトテーマに切り替えることができます。

まとめ

今回は自作のブログサイトにダークモード切り替えボタンを実装したときの話を書きました。
Vuetifyを利用すれば簡単に実装できるのがいいですね!
「$vuetify.theme.dark」の真偽値を変更すれば切り替えられますからね。
みなさんも是非実装してみてください。
それでは今回はここで筆を置かせていただきます。
最後まで記事をご覧いただきありがとうございました!

関連記事

この記事に関連するおすすめです。