Blog

Vue 3: How to Add Body Class Based on Current Route

In Vue.js applications, dynamically updating the body class based on the current route can be a handy feature. Whether you're styling different sections of your application or implementing route-specific functionality, having this capability can enhance the user experience. In this article, we'll explore how to achieve this in Vue 3 using Vue Router.

Setting Up Vue Router

Firstly, ensure you have Vue Router installed in your Vue 3 project. If not, you can install it via npm:

npm install vue-router@next

Title: Vue 3: How to Add Body Class Based on Current Route

In Vue.js applications, dynamically updating the body class based on the current route can be a handy feature. Whether you're styling different sections of your application or implementing route-specific functionality, having this capability can enhance the user experience. In this article, we'll explore how to achieve this in Vue 3 using Vue Router. Setting Up Vue Router

Firstly, ensure you have Vue Router installed in your Vue 3 project. If not, you can install it via npm:

bash

npm install vue-router@next

After installation, set up Vue Router in your application. Here's a basic setup in your main.js or app.js file:

import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import App from './App.vue'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About },
    // Add more routes as needed
  ]
})

router.beforeEach((to, from, next) => {
  document.body.classList.remove('route-' + from.name)
  document.body.classList.add('route-' + to.name)
  next()
})

createApp(App).use(router).mount('#app')

Adding Body Class Dynamically

In the setup above, we're using Vue Router's beforeEach navigation guard. This guard is invoked before each navigation to a new route. Within this guard, we remove the class associated with the previous route from the body and add the class corresponding to the new route. Styling Routes

With the body class being updated dynamically, you can now style your routes in your CSS or SCSS files:

/* styles.css */

.route-home {
  /* styles for home route */
}

.route-about {
  /* styles for about route */
}

/* Add more route-specific styles as needed */

By applying these styles, you can tailor the appearance of your application based on the active route, providing a more engaging user experience.

Conclusion

Dynamic body classes based on the current route in Vue 3 applications can be a powerful tool for styling and enhancing user interaction. With Vue Router's navigation guards and a few lines of code, you can easily implement this feature and take your Vue.js projects to the next level. Happy coding!