LoginSignup
16
10

More than 3 years have passed since last update.

Vuetifyでダークとライトテーマを切り替える機能を実装する

Posted at

下記の画像のように、Vuetifyでダーク(dark)とライト(light)テーマを切り替える機能を実装する方法です。

ezgif.com-video-to-gif.gif

ダークとライトテーマを切り替える機能

<template>
  <div>
    <v-switch
      v-model="theme"
      :prepend-icon="themeIcon"
    ></v-switch>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'

export default Vue.extend({
  data() {
    return {
      theme: true
    }
  },
  computed: {
    themeIcon(): string {
      return this.theme ? 'mdi-weather-night' : 'mdi-weather-sunny'
    }
  },
  watch: {
    theme() {
      this.$vuetify.theme.dark = this.theme
    }
  }
})
</script>

v-model="theme"として、watchで監視します。
this.$vuetify.theme.dark = true or falseでダークとライトテーマを切り替えています。

見栄えの為にcomputedでアイコンの変更も実装しています。

テーマごとのカラー設定

nuxt.config.js
import colors from 'vuetify/es5/util/colors'

export default {
  /*
   ** vuetify module configuration
   ** https://github.com/nuxt-community/vuetify-module
   */
  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
        },
        light: {
          primary: colors.red.darken2,
          accent: colors.blue.darken3,
        }
      }
    }
  }
}

テーマごとのカラーの設定はnuxt.config.jsで行うことができます。

最後に

Vuetifyを使えば簡単にテーマの切り替えが実装できるので便利です。

16
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
10