【问题标题】:Vue- How to change style of a same element in different componentsVue-如何更改不同组件中相同元素的样式
【发布时间】:2019-04-18 21:32:42
【问题描述】:

我正在尝试将特定 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>

【问题讨论】:

  • 如果出现两次,应该不会有相同的id
  • @RoyJ 请仔细阅读,id app 只有一个实例。组件中的模板被注入到 App.vue 模板中。

标签: html css vue.js


【解决方案1】:

通过检查路由路径可以快速完成此操作(不确定是否是最佳做法);假设Hello.vue 是通过路径/hello 渲染的:

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

【讨论】:

  • 完美运行!谢谢!如果你碰巧找到了直接在 css 中实现的方法,请告诉我。
  • 我该如何添加这一行? margin-left: ($route.path === ('/app/my-account' || '/app/fleet-overview' || '/app/rankings')?'10%':'')我似乎找不到将其添加到您的答案中的方法。
  • 试试margin-left: (['/app/my-account', '/app/fleet-overview', '/app/rankings'].includes($route.path) ? '10%':'')
猜你喜欢
  • 1970-01-01
  • 2020-08-14
  • 2018-04-13
  • 1970-01-01
  • 1970-01-01
  • 2020-07-25
  • 1970-01-01
  • 1970-01-01
  • 2017-03-29
相关资源
最近更新 更多