1、問題
使用 vue 時寫發現某些樣式不生效,怎么都不生效, 不過將style 中的 scoped 去掉后,居然生效了。但是一般都應該加上scoped,那該如何處理呢?
<template>
<div class="app-container">
<heads />
<div class="login-body">
<el-steps :active="active" finish-status="success" size="medium" :space="400" :align-center="true" style="width: 800px">
<el-step title="創建帳戶" />
<el-step title="完善信息"/>
<el-step title="注冊成功"/>
</el-steps>
<!--創建帳戶-->
<el-card class="card" style="margin-top: 50px;width:1000px;">
<account v-if="active==1" :obj="obj" ref="account" @clickNext="next($event)"/>
<!--完善信息-->
<info
v-if="active==2 "
ref="info"
:obj="obj"
@click="closeDialog()"
@clickPrev="prev($event)"
@clickNext="next"/>
<!--注冊成功-->
<success
v-if="active==3"
ref="success"
@clickPrev="prev()"/>
</el-card>
<!-- </el-dialog>-->
</div>
<bottom />
</div>
<!-- </div>-->
</template>
效果如下:

添加scoped與不添加scoped時樣式的區別:
不添加scoped:

添加scoped:

2、原因:
vue的scoped為本組件的所有標簽都打上了一個唯一attribute,如上圖的紅框內的data-v-ee52e422,有data-v-ee52e422的標簽都是本組件的標簽,樣式生效時也帶上了這唯一的attribute,但是本組件的所有子組件,除根標簽el-step以外其他都未打上這唯一標簽,因此樣式自然不會生效。
3、解決辦法
vue給出的解決辦法是: 深度作用選擇器
如果你希望 scoped 樣式中的一個選擇器能夠作用得“更深”,例如影響子組件,你可以使用 >>> 操作符
有些像 Sass 之類的預處理器無法正確解析 >>>。這種情況下你可以使用 /deep/ 或 ::v-deep 操作符取而代之——兩者都是 >>> 的別名,同樣可以正常工作。
通常我們會選擇/deep/,使用方式如下,在需要子組件樣式生效的地方加上/deep/
.login-body { width: 100%; height: 90%; display: flex; flex-direction: column; justify-content: center; align-items: center; /deep/.el-step__icon{ width: 50px; height: 50px; } }
或者
.login-body { width: 100%; height: 90%; display: flex; flex-direction: column; justify-content: center; align-items: center; ::v-deep .el-step__icon{ width: 50px; height: 50px; } }
效果如下:

修改線的位置
.login-body { width: 100%; height: 90%; display: flex; flex-direction: column; justify-content: center; align-items: center; ::v-deep .el-step__icon{ width: 50px; height: 50px; } ::v-deep .el-step__line{ top: 25px; } }
其中el-step__line的樣式如下

效果如下:

