I\'m using Vue router with two pages:
let routes = [
{
path: \'/\',
component: require(\'./components/HomeView.vue\')
},
{
pa
I got it working with the lifecycle hook beforeCreate
and a global stylesheet. In global.css
:
body.home {
background: red;
}
body.intro {
background: pink;
}
In the <script>
section of HomeView.vue
:
export default {
beforeCreate: function() {
document.body.className = 'home';
}
}
And similar in IntroView.vue
.
If the class is view specific, may be this will help
methods: {
toggleBodyClass(addRemoveClass, className) {
const el = document.body;
if (addRemoveClass === 'addClass') {
el.classList.add(className);
} else {
el.classList.remove(className);
}
},
},
mounted() {
this.toggleBodyClass('addClass', 'mb-0');
},
destroyed() {
this.toggleBodyClass('removeClass', 'mb-0');
},
Move the methods
section to a mixin and then the code can be DRY.
You can also do it directly in the router file using the afterEach
hook:
mainRouter.afterEach((to) => {
if (["dialogs", "snippets"].includes(to.name)) {
document.body.style.backgroundColor = "#F7F7F7";
// or document.body.classList.add(className);
} else {
document.body.style.backgroundColor = "#FFFFFF";
// or document.body.classList.remove(className);
}
});
afterEach hook documentation
to
is a route object which contains the route name (if named), path, etc. Documentation for all the props
You can use scoped attribute in the style element. Then the style will be limited only to that vue file.
HomeView.vue:
<template>
<p>This is the home page!</p>
</template>
<script>
export default {
}
</script>
<style scoped>
body {
background: red;
}
</style>
IntroView.vue:
<template>
<div>
<h1>Introduction</h1>
</div>
</template>
<script>
export default {
}
</script>
<style scoped>
body {
background: pink;
}
</style>
watch: {
$route: {
handler (to, from) {
const body = document.getElementsByTagName('body')[0];
if (from !== undefined) {
body.classList.remove('page--' + from.name.toLowerCase());
}
body.classList.add('page--' + to.name.toLowerCase());
},
immediate: true,
}
},
Another fairly simple solution, add it to your base App.vue file. The to.name can be replaced with to.meta.class or similar for something more specific. This is a nice do it once and it works forever type solution though.
Alternatively you can use this
It allows to control your page body classes with vue-router. Wrote this when faced the similar issue. It also refers to Add a class to body when component is clicked?