Home > Software engineering >  How to reactively set a <html> class
How to reactively set a <html> class

Time:03-11

I have 2 themes: 'light-theme', 'dark-theme' I would like to set the <html > 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)

CodePudding user response:

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 );
    },
  }

CodePudding user response:

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

1.Binding to Objects

<div :></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 :></div>

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

  • Related