Vue-如何更改不同组件中同一元素的样式

时间:2018-11-15 17:49:43

标签: html css vue.js

我正在尝试将特定div的样式从一个组件更改为另一个组件。每个组件都将附加到App组件中的模板,并替换<router-view></router-view>标签。 div #app的Hello.vue组件中必须有172px的填充,其余组件中必须有0px的填充。这有可能吗,我该如何实现?

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 个答案:

答案 0 :(得分:2)

有一种快速的方法可以通过检查路径来做到这一点(不确定是否是最佳实践);假设Hello.vue是通过路径/hello呈现的:

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