天天看点

vue样式scoped属性以及不生效

scoped 作用

<style scoped>
.content {
	font-size: 14px;
}
</style>
           

实现组件样式的私有化,不对全局造成样式污染。

例如:

/* A组件样式对字体设置为红色 */
<style>
.content {
	font-size: 16px;
	color: red;
}
</style>

/*B组件对样式字体不设置颜色 */
<style>
.content {
	font-size: 16px;
}
</style>
           

上述如果我们交错点击A或者B组件,会造成B组件的字体也变成红色

scoped实现原理

通过在DOM结构以及css样式上加上唯一的标记,保证唯一,达到样式私有化,不污染全局的作用,如图,样式属性上也会多一个该字符,以保证唯一

加上scoped样式名称变成如下:

<style scoped>
.content {
	font-size: 16px;
}
</style>

.content[data-v-469af010] {
	font-size: 16px;
}
           

不生效情况

父子组件都有scoped属性