美文网首页
Vue组件修改子组件的css样式

Vue组件修改子组件的css样式

作者: 手指乐 | 来源:发表于2019-10-13 18:11 被阅读0次
  • 子组件:
<template>
  <div id="demo">
    <div class="inner">haha</div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      items: ['html', 'css', 'js']
    };
  },
  methods: {
    clear(){
      this.items.splice(0);
    },
    reset(){
      history.go();
    }
  }
};
</script>

<style scoped>
#demo{
  background-color: red ;
  height: 100px;
}
.inner{
  height: 50px;
  background-color: blue;
  color:white;
}
</style>
  • 父组件
<template>
  <div id="app">
    <img src="./assets/logo.png">
    <router-view/>
  </div>
</template>

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

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
  • 使用 scoped 后,父组件的样式将不会渗透到子组件中。不过一个子组件的根节点会同时受其父组件的 scoped CSS 和子组件的 scoped CSS 的影响。这样设计是为了让父组件可以从布局的角度出发,调整其子组件根元素的样式
    父组件中增加
<style scoped>
#demo {
  width: 100px;
  height: 200px !important;
}
</style>

这个样式对子组件是有效的,其中height要加上important,因为子组件中已经有了height,会覆盖父组件的样式

  • 浏览器中查看源码,可以发现如果子组件的样式中增加了scope,会在每个元素的属性中增加一个属性,比如data-v-dc87507c
<div data-v-dc87507c="" data-v-469af010="" id="demo">
    <div data-v-dc87507c="" class="inner">haha</div>
</div>

父组件中的css也是scope的,所以父组件元素也会增加一个类似的属性
子组件的根组件增加了两个属性,其中一个(data-v-469af010)对应父组件增加的属性
vue同时会把我们定义的样式的选择器加上一个属性选择器,比如上面父组件中的

#demo {
  width: 100px;
  height: 200px !important;
}

实际上是:

#demo[data-v-469af010] {
    width: 100px;
    height: 200px !important;
}

由于子组件的根元素含有父组件的这个属性,所以这个样式可以影响到子组件
而子组件的其他元素不含有父组件的这个属性,所以不会受到父组件样式的影响
比如父组件中增加样式:

.inner{
  font-size: 20px;
}

是无效的
因为inner会转为inner[data-v-469af010],inner对应的子组件div并没有加上父组件的这个属性

  • 上例中如果父组件css不加scope
#demo {
  width: 100px;
  height: 200px !important;
}

这个也不会自动增加属性选择器,但是也可以作用到子组件的根元素
因为通过id已经可以选择到子组件对应的元素,属性选择器可以不加,但是不能加错,加对了的话,选择器的权重更高
同理

.inner{
  font-size: 20px;
}

也是有效的

  • 上例中如果子组件css不加scope,父组件有scope
    则父组件中#demo样式对子组件有用
    .inne无用
    原理还是因为属性选择器

  • 上例中如果子组件css不加scope,父组件也不加scope
    则父组件中#demo样式对子组件有用
    .inne也有用
    原理还是因为属性选择器

  • 把父组件的scoped去掉,就可以在父组件中修改子组件的样式
    为了减少全局css污染,vue组件可以同时用scoped和非scoped的css

<style>
/* 全局样式 */
</style>
<style scoped>
/* 本地样式 */
</style>
  • 引入一个外部全局的css,在这个css里控制,也可以在父组件中修改子组件的样式
    common.css:
.inner {
    font-size: 40px;
}

父组件中引入:

import '../style/common.css'

外部css文件不加属性选择器,所以对子组件有用

  • 使用深度作用选择器,也可以在父组件中修改子组件的样式:
#demo >>> .inner {
    font-size: 40px;
}

深度作用选择器语法:父组件根元素选择器 >>> 子组件选择器

如果是sass或less这种预编译语法
则 不支持 >>> 这种形式
有另外一种形式支持: /deep/
/deep/同时也支持css

#demo /deep/ .inner {
    font-size: 40px;
}

相关文章

网友评论

      本文标题:Vue组件修改子组件的css样式

      本文链接:https://www.haomeiwen.com/subject/hpkkmctx.html