Vue- How to change style of a same element in different components

Viewed 4022

I am trying to change the style of a specific div from one component to another. Each component is appended to the template in the App component and replaces the <router-view></router-view> tags. The div #app needs to have a padding of 172px in the Hello.vue component, and 0px on the rest of the components.Is this possible, and how can I accomplish this?

App.vue

<template>
  <div id="app">
    <div>
      <img src="./assets/logo.png" align="center">
    </div>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'app'
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  background-color: hsla(275, 97%, 50%, 0.57);
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 0px;
  height: inherit;
}

body{
  height: inherit;
}

html{
  height: 100%;
}
</style>

Hello.vue

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <ul>
      <li><h2><router-link to="/app/login">Login</router-link></h2></li>
      <li><h2><router-link to="/app/about">About Us</router-link></h2></li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'hello',
  data () {
    return {
      msg: 'Welcome to Vue'
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

#app{ 
    padding-top: 172px; /*This does not work*/
}

h1, h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #000000;
}
</style>
1 Answers

There is a quick way to do this (not sure if it's best practice) by checking the route path; assume Hello.vue is rendered via the path /hello:

<div id="app" :style="{ padding: $route.path === '/hello' ? '172px' : '0px' }">
  ...
</div>
Related