Changing body styles in vue router Changing body styles in vue router vue.js vue.js

Changing body styles in vue router


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.


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?