Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuetify conditional dark theme

I'm using Vuetify to create my social media website. The problem that I'm facing now is that I want to use dark attribute, so user can switch between normal and dark theme. The thing is that I can't use any of Vue's conditional rendering methods, as dark is not an attribute that you can bind. Below is the part of code that you use to apply dark theme:

<v-app dark>
like image 396
Dawid Cyron Avatar asked May 09 '18 07:05

Dawid Cyron


4 Answers

To be able to persist theme with localstorage

Inside plugins/vuetify.js or plugins/vuetify.ts add this:

export default new Vuetify({
  theme: {
    //
    dark: localStorage.getItem('theme') === 'dark',
    //
  }
})

then on the button you want to switch theme apply the following function:

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

  localStorage.setItem('theme', this.$vuetify.theme.dark ? 'dark' : 'light');
}
like image 123
Alvin Konda Avatar answered Oct 21 '22 09:10

Alvin Konda


Yes dark or light are not attributes, they are props which can take values, in this case true or false

You can find this in vuetify's documentations.

dark theme light theme

Props are the properties which are used for communication with child components. And are prefixed with : in order to distinguish it with normal properties.

Coming to the solution.

<v-app :dark="true"> 

or

<v-app :dark="false"> 

You can replace true or false with any reactive data options or computed properties to make the theme change programmatically.

like image 15
Ankit Kumar Ojha Avatar answered Oct 21 '22 09:10

Ankit Kumar Ojha


As documentation says you can just update variable this.$vuetify.theme.dark:

You can manually turn dark on and off by changing this.$vuetify.theme.dark to true or false.

like image 3
volkovs Avatar answered Oct 21 '22 11:10

volkovs


If a component is used as the App:

<template>
   <v-app :dark="isDark"></v-app>
</template>

<script>
   export default {
      data () {
         return {
            isDark: false,
         }
      },
   }
</script>

It can also be called from the app instance

thru its instantiated object defined property app.__vue__.isDark = isDark when being instantiated like :

const app = new Vue(
    {
        data: () => ({
            isDark: false
        }),
    }
)

So it can be called from other component

like image 1
Nicolas Cabanas Avatar answered Oct 21 '22 09:10

Nicolas Cabanas