问题背景
在使用vue构建项目的时候,引用了第三方组件库,只需要在当前页面修改第三方组件库的样式,以做到不污染全局样式。通过在样式标签上使用scoped,达到样式只作用到本页面的目的,但是此时再修改组件样式就不起作用了。
<div class="text-box" v-html="emotion(item.content)"></div>
<style lang="stylus" scoped>
.text-box{
color: #2e3135;
font-size: 14px
line-height 20px
max-height 50px
display: -webkit-box;
-webkit-box-orient: vertical;
text-overflow: ellipsis;
overflow: hidden;
-webkit-line-clamp: 2
}
</style>
vue中的scoped属性的效果主要通过PostCSS转译实现
<div data-v-3ef06b24="" class="text-box">
<h3 style="color:#1E90FF" ;="">
<strong>【数说·有奖互动】第8期 #技术干货# 运维经验分享</strong>
</h3>
【参与规则】:在#技术干货#话题下发数说,分享您的运维工作经验/有趣故事。
(比如给大家分享一个故障处理经过。如篇幅较长,建议发文章然后插入链接到数说)
【活动奖励】:我们将根据内容质量和互动热度选3位网友送《程序员面试笔试宝典》
或以下任选图书1本,同时也会抽 5 位幸运鹅,送50墨值奖励~
【活动时间】:8月12日——8月19日10:00
</div>
<style lang="stylus" scoped>
.text-box[data-v-3ef06b24] {
color: #2e3135;
font-size: 14px;
line-height: 20px;
max-height: 50px;
display: -webkit-box;
-webkit-box-orient: vertical;
text-overflow: ellipsis;
overflow: hidden;
-webkit-line-clamp: 2;
}
</style>
简单原理
通过 >>> 穿透scoped,iview中需要在组件上使用i-class声明第三方组件类名
<style scoped>
外层 >>> 第三方组件类名{
样式
}
</style>
穿透方法实际上违反了scoped属性的意义。而且在vue中过多使用scoped,导致页面打包文件体积增大。
通常能写在index中的样式尽量写在index中,我们可以通过在index样式中通过外层组件添加唯一class来区分组件+第三方样式来实现类似于scoped的效果,又方便修改各种第三方组件的样式。
应用
<div class="text-box" v-html="emotion(item.content)"></div>
<style lang="stylus" scoped>
.text-box{
color: #2e3135;
font-size: 14px
line-height 20px
max-height 50px
display: -webkit-box;
-webkit-box-orient: vertical;
text-overflow: ellipsis;
overflow: hidden;
-webkit-line-clamp: 2;
& >>> strong {
font-size: 14px
overflow: hidden;
line-height 20px
}
}