How to add CSS class dynamically on the HTML body in Nuxt
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.
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
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>