How to add a class to body tag in Vue.js

in Code Write a comment

In this tutorial, you’ll learn how to add and remove body classes in Vue.js with and without using additional packages.

You already know that there is an npm package for almost anything e.g. vue-body-class. It allows you to add route-specific classes to your body tag.

It’s useful if you have a lot of routes in your project that need different classes. However, if you just need to add a class only on a few routes e.g. log in, sign up and password reset pages I suggest using plain JavaScript without additional packages.

Method #1

mounted () {
  document.body.classList.add('bg-light')
},
destroyed () {
  document.body.classList.remove('bg-light')
}

The code above will add a bg-light class to the body tag when the component is mounted. The class will get deleted when you open another page (route).


Hi, I'm Renat 👋

 


If you want to add or remove multiple classes in JavaScript you can separate them with comma.

mounted () {
  document.body.classList.add('bg-light', 'login')
},
destroyed () {
  document.body.classList.remove('bg-light', 'login')
},

As you see it’s faster than installing a third-party package and setting it up. But only if you want to add classes on a few routes.

Method #2 using vue-body-class package

You can use this package to control body classes. I only recommend using it if you have a lot of routes that require different classes.

{
  path: '/login',
  name: 'login',
  component: Login,
  meta: { bodyClass: 'bg-light' }
}

If you find this post useful, please let me know in the comments below. 
Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/vue-js-body-class

PS: You can also check how to get the first item in Vue.js array and other Vue.js tutorials.

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment

Comment

6 Comments