scoped 和/deep/的作用

今天在写代码时,要更改element ui 的组件样式,调试了半天发现更改都没作用,后来请教了同事,他说你需要用到深度选择器 ,我用了一下,瞬间生效.下面总结一下何为深度选择器吧.

/deep/ 深度选择器

/deep/的意思大概为深入的,深远的。

在vue中,我们为了避免父组件的样式影响到子组件的样式,会在style中加<style scoped>,这样父组件中如果有跟子组件相同的class名称或者使用选择器的时候,就不会影响到子组件的样式。

父组件:

<template>
    <div>
        <h1 class="title">{
    
    {
    
     name }}</h1>
        <input type="text" v-model.lazy="name">
        <child />
    </div>
</template>

<script>
import child from './child';
export default {
    
    
    data () {
    
    
        return {
    
    
            name:''
        }
    },
    components: {
    
    
        child
    }
}
</script>
<style scoped>
     .title{
    
    
        color: #ff0;
    }
</style>

子组件:

<template>
    <div>
        <h1 class="title">child</h1>
    </div>
</template>
<script>
export default {
    
    
    
}
</script>
<style scoped>
    .title{
    
    
        color:#f00;
    }
</style>

我们在加了 scoped 之后样式会自动添加一个hash值,如下:

.title[data-v-211e4c4a] {
    
    
    color: #ff0;
}

但是这样也存在着一个问题,比如你使用了别人的组件或者自己开发一个组件,有时候你修改一处就可能影响到别的地方,这个时候要么你不用别人的组件,自己重新封装一个,但很多时候是不太现实的,所以就需要有一个方法或者方式,既不影响到别的地方,又能修改子组件在当前的样式。

那么我们就需要/deep/,使用方式也很简单:

<style scoped>
     /deep/ .title{
    
    
        color: #ff0;
    }
</style>

当然了把/deep/换成 >>>,也可以达到同样的效果。

猜你喜欢

转载自blog.csdn.net/qq_27674439/article/details/108317700
今日推荐