How to add a class to HTML body in Vue

Vue guide logo

Adding Class in HTML body in Vue

We will be leveraging unHead from Unjs plugin, allowing us to add a class in the HTML body in Vue 3 and Typescript. Video of this tutorial available at the bottom of this page.

Looking for tutorial onĀ how to do it in Nuxt?

1. Install unHead

yarn add unhead

2. Register the plugin in the Vue app

typescript
import { createApp } from "vue";
import { createHead } from 'unhead';

const app = createApp();
const head = createHead();

app.mount("#app");

3. In the Vue app or component template tag

In the template below, we have a click function called handleClick and it was attached to the button.

html
<template>
  <div>
    <h1>Click the button</h1>
    <button @click="handleClick">Click here</button>
  </div>
</template>

4. In Vue script tag

Inside Vue script tag, we created a handleClick function that is attached to a button. When the button clicked, it will change the isActive value.

We imported useHead from unHead then we add bodyAttrs property with a key of class. The class value is a computed property that we watch.

typescript
<script lang="ts" setup>
import { useHead } from 'unhead'
import { computed, ref } from 'vue';

const isActive = ref(false);
const handleClick = () => {
  isActive.value = !isActive.value;
};

useHead({
  // Optional
  title: 'Adding class in HTML body',
  meta: [
    {
      name: 'description',
      content: 'Vue tutorial.'
    }
  ],
  // This is where we can add a class in to the HTML body
  bodyAttrs: {
    class: computed(() => (isActive.value ? 'body-class' : ''))
  }
});
</script>

Video tutorial

Previous post How to get query parameters in Vue
Next post How to deploy Vue app in Microsoft Azure