Crafting a Dark Mode switch with Vuetify
Nathan Sheryak
Posted on April 28, 2021
This tutorial will show how to create a dark mode toggle using Vuetify. This tutorial assumes you already have a Vue2 app with Vuetify. At the time of writing this article Vuetify doesn't fully support Vue3.
Here is an accompanying GitHub repository if you'd like to have a working copy to clone.
Step 1: Modifying vuetify.js
vuetify.js
is a file that gets created when you first add Vuetify to your Vue application. It can be found here: src/plugins/vuetify.js
. We will make the modifications below.
import Vue from 'vue';
import Vuetify from 'vuetify/lib/framework';
import colors from 'vuetify/lib/util/colors'
Vue.use(Vuetify);
export default new Vuetify({
theme: {
themes: {
light: {
primary: colors.green.accent3,
secondary: colors.deepOrange.lighten1
},
dark: {
primary: '#90CAF9',
secondary: '#E91E63'
},
},
},
});
You can set these colors to be what ever you'd like, just make sure if you have a primary
color for your light theme
that you have one for your dark theme
as well.
If you want to use the colors built into Vuetify, make sure you import the color library on line 3. You can always use hex instead, but you will need to place it in quotes (I did that in the dark theme as an example).
Step 2: Adding a toggle
The documentation on vuetify switches uses a v-model
to bind the data. We want to break that v-model
out into a :value=""
that reads the data from the data object, and an @change=""
that will trigger a method. This setup allows for greater flexibility on what the switch will do.
Inside of the toggleDarkMode()
we want to switch the Vuetify theme. We can access the Vuetify theme using this.$vuetify.theme
, here is the documentation for it: this.$vuetify.theme.
<template>
<v-app>
<v-app-bar app color="primary">Dark Mode Toggle</v-app-bar>
<v-main>
<v-container>
<v-switch
:value="darkMode"
@change="toggleDarkMode"
:label="`toggle ${switchLabel} mode`"
></v-switch>
<v-col class="primary">I am a primary card</v-col>
<v-col class="secondary">I am a secondary card</v-col>
</v-container>
</v-main>
</v-app>
</template>
<script>
export default {
name: 'App',
data: () => ({
darkMode: false
}),
methods: {
toggleDarkMode: function () {
this.$vuetify.theme.dark = !this.$vuetify.theme.dark;
this.darkMode = !this.darkMode;
}
},
computed: {
switchLabel: function () {
return this.darkMode ? 'light' : 'dark';
}
}
};
</script>
There you have it! A switch that toggles between a light and dark theme!
Vuetify is a living, changing UI Library. Specifics of this article may change over time. If you notice something is out of date, feel free to contact me. Happy designing!
Posted on April 28, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.