vue组件的样式穿透 /deep/ ::v-deep的使用

1.我们在开发过程中,会使用很多组件,也会出现组件服用的情况,我们在书写组件时,往往会在style样式中使用scoped属性,表明样式只在当前组件生效,很好的实现了样式私有化的目的,避免了样式之间的互相污染与冲突。

2.但是我们在使用可复用性组件的时候,往往不可避免的遇到组件相同而样式不同的情况。这时我们就需要样式穿透,在父组件中写样式来作用在子组件身上,或者作用在孙子组件上,可跨越多个组件。

3.子组件

<template>

  <div class="son"></div>

</template>

<style scoped lang="less">

.son {

  width: 400px;

  height: 400px;

  background-color: yellow;

}

</style>

这时son背景颜色是黄色

4.父组件

<style scoped lang="less">

/deep/ .son{

  background-color: pink;

}

</style>

这时son背景颜色变为粉色

<style scoped lang="less">

::v-deep .son{

  background-color: red;

}

</style>

这时son背景颜色变为红色

5.爷孙组件样式穿透

<template>

    <div>

        <div class="grandSon">

            我是孙子组件

        </div>

    </div>

</template>

<style scoped  lang="less">

.grandSon{

    width: 100%;

    height: 100px;

    background-color: yellow;

    font-size: 30px;

    color: red;

}

</style>

此时孙子组件背景颜色为黄色

子组件引入、注册、使用。

然后父组件引入子组件、注册、使用。

<style scoped lang="less">

/deep/ .grandSon{

  background-color: pink;

}

</style>

此时孙子组件背景颜色变为粉色

<style scoped lang="less">

::v-deep .son{

  background-color: red;

}

</style>

 此时孙子组件背景颜色变为红色


版权声明:本文为weixin_67490903原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。