Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing body styles in vue router

Tags:

I'm using Vue router with two pages:

let routes = [     {         path: '/',         component: require('./components/HomeView.vue')     },     {         path: '/intro',         component: require('./components/IntroView.vue')     } ] 

This works fine, except that each of my components has different body styling:

HomeView.vue:

<template>     <p>This is the home page!</p> </template>  <script>     export default {      } </script>  <style>     body {         background: red;     } </style> 

IntroView.vue:

<template>     <div>         <h1>Introduction</h1>     </div> </template>  <script>     export default {      } </script>  <style>     body {         background: pink;     } </style> 

My goal is to have these two pages have different background styles (eventually with a transition between them). But at the moment when I go to the home route (with the red background), then click the intro route, the background colour stays red (I want it to change to pink).

Edit: index.html:

  <body>     <div id="app">         <router-link to="/" exact>Home</router-link>         <router-link to="/intro">Introduction</router-link>         <router-view></router-view>     </div>     <script src="/dist/build.js"></script>   </body> 
like image 574
GluePear Avatar asked Jun 14 '17 10:06

GluePear


People also ask

How do I use style CSS in vue?

Adding CSS classes in Vue We should apply the button CSS classes to the <button> in our ToDoForm component. Since Vue templates are valid HTML, this is done in the same way to how you might do it in plain HTML — by adding a class="" attribute to the element.

Can we modify props in vue?

Note: Props are read-only, which means the child component cannot modify them because the data is owned by the parent component and is only passed down to the child component to read it.

What is hash mode in vue router?

The default mode for vue-router is hash mode - it uses the URL hash to simulate a full URL so that the page won't be reloaded when the URL changes. To get rid of the hash, we can use the router's history mode, which leverages the history.

What is redirect in vue router?

A redirect means when the user visits /home , the URL will be replaced by / , and then matched as / . But what is an alias? An alias of / as /home means when the user visits /home , the URL remains /home , but it will be matched as if the user is visiting / .


1 Answers

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.

like image 108
GluePear Avatar answered Sep 18 '22 19:09

GluePear