Maxim
Maxim

Reputation: 447

How to reactively set a <html> class

I have 2 themes: 'light-theme', 'dark-theme' I would like to set the <html class=""> according to a value i have in my vuex store. Like darkMode: true

How can i set the <html> class reactively like that?

(using vue3)

Upvotes: 0

Views: 358

Answers (2)

gguney
gguney

Reputation: 2643

You can use simple javascript for it.

Just add a button or toggle for theme change like:

<button @click="changeTheme">Change Theme</button>

and inside this component add changeTheme method inside methods:

document.getElementsByTagName("html")[0].setAttribute( 'class', 'newThemeClass' );

Or just add watcher to your store value and change according to it:

computed:{
    ...mapGetters(["yourGetterName"])
 },
watch: {
    darkMode(value) {
      document.getElementsByTagName("html")[0].setAttribute( 'class', value );
    },
  }

Upvotes: 1

Nabil Ahmad
Nabil Ahmad

Reputation: 221

According to Vue docs, there are following ways to do this.

1.Binding to Objects

<div :class="{ 'active-class': isActive }"></div>

The above syntax means the presence of the 'active-class' class will be determined by the truthiness of the data property isActive.

2.Binding to Arrays

<div :class="[isActive ? activeClass : '', errorClass]"></div>

This will always apply errorClass, but activeClass will only be applied when isActive is truthy.

Upvotes: 1

Related Questions