How to add CSS class dynamically on the HTML body in Nuxt

Nuxt guide logo

Nuxt 3

In Nuxt 3, to add dynamic class in to the body, use useHead composables within the script tag, this code also written in Typescript. Video of this tutorial available at the bottom of this page.

Looking for tutorial on how to do it in Vue?

Inside script tag:

                                
                                        <script lang="ts" setup>
// create variable for mobile navigation
const isMobileNavVisible = ref<boolean>(false);
// method when the menu button is click
const menuTrigger = (): void => {
  if (isMobileNavVisible.value) {
    isMobileNavVisible.value = false;
    return;
  }

  isMobileNavVisible.value = true;
};
// useHead composable to add CSS class in the HTML body
// when the menu trigger is click
useHead({
  bodyAttrs: {
    class: computed(() => {
      if (isMobileNavVisible.value) return 'menu-is-open';
      
      return '';
    }),
  },
});
</script>
                                    
                            

Inside .vue template:

                                <template>
  <section>
    <button @click="menuTrigger()">Click this button</button>
  </section>
</template>
                            

Nuxt 2

This code for Nuxt 2 is written using Composition API with TypeScript, which needs to be install first.

Inside script tag:

                                
                                        <script lang="ts">
import { ref, defineComponent } from '@nuxtjs/composition-api';

export default defineComponent({
  name: 'ComponentName',
  head() {
    return {
      bodyAttrs: {
        class: `${this.bodyClass}`,
      },
    };
  },
  setup() {
    // Variable to hold class name
    const bodyClass = ref('');
 
    // Button click method
    const onClick = () => {
      // Set class when button is clicked
      bodyClass.value = 'menu-is-open';
    }
 
    return {
      bodyClass,
      onClick,
    };
  },
});
</script>
                                    
                            

Inside .vue template:

                                <template>
  <section>
    <button @click="onClick"></button>
  </section>
</template>
                            

Video tutorial

Previous post How to Fetch GraphQL API with Nuxt's Composition API
Next post How to use Markdown content in Nuxt 2 and Typescript