I'm working on a Nuxt 3 project, and I want to replace the body class on route change using the useHead hook. Specifically, I want to use useFetch to load data for the current page, and once that data is resolved, I want to use data.bodyclass to replace the body class of the document.
Here's what I use:
useHead({
bodyAttrs: { class: `page--${data.bodyClass}`
});
The problem with this code is that it adds data.bodyclass to the existing body class, rather than replacing it. What's the best way to replace the body class using useHead in this scenario?
After changing route the body looks like
<body class='class-loaded-for-page-1 class-loaded-for-page-2'> but I want it result in <body class='class-loaded-for-page-2'>
I can't use vanilla document.body.classlist to modify the class-attribute as i use SSR where document is not defined.
Thanks for any help you can provide!
I think one of the reasons is your code is incorrect. You are missing an end curly bracket inside the useHead composable.
// Incorrect
useHead({
bodyAttrs: { class: `page--${data.bodyClass}`
});
// Correct
useHead({
bodyAttrs: {
class: `page--${home.value}`
}
})
Try fixing that and it should be working. I made an example and it works https://codesandbox.io/p/sandbox/intelligent-hermann-59ifef
Inspect element the code. Make sure you are inspecting the correct body tag. It should be inside an iframe

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With