Changing body styles in vue router
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.
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.