页面style的scoped默认是开启的,如果一个组件渲染后后包括子标签,会造成页面自己写的样式无效

UniApp页面样式默认规则是:H5端为了隔离页面间的样式默认启用了scoped

问题详情

渲染前的页面样式代码,style并未设置scoped,写在外部文件引用也一样,UniApp默认是开启的

<style>
	switch.blue-checked.uni-switch-input {
		background-color: #007aff !important;
		border-color: #007aff !important;
		color: #ffffff !important;
		border-color: #007aff !important;
	}
</style>

 渲染后的css代码,会自动添加data-v-xxxxxx属性

uni-switch.blue-checked.uni-switch-input[data-v-82079b42] {
 	background-color: #007aff !important;
 	border-color: #007aff !important;
 	color: #ffffff !important;
    border-color: #007aff !important;
}

组件渲染生成的switch组件代码,生成了很多子标签,但只在本组件加上了scoped的data-v-xxxxxx,子标签未自动添加,所以上面渲染后的css代码就无法生效

<uni-switch data-v-82079b42="" class="blue-checked">
	<div class="uni-switch-wrapper">
		<div class="uni-switch-input uni-switch-input-checked"
			style="background-color: rgb(0, 122, 255); border-color: rgb(0, 122, 255);"></div>
		<div class="uni-checkbox-input uni-checkbox-input-checked" style="color: rgb(0, 122, 255); display: none;">
		</div>
	</div>
</uni-switch>

解决办法

1、使用scoped穿透 

css使用 >>> .test{ xxx }
scss、less使用 /deep/ .test{ xxx }

css中使用>>>来标识scoped的data-v-xxxxxx所在位置,>>>可以写在任何位置,写在哪,data-v-xxxxxx就生成在哪里,如下

<style>
	switch.blue-checked>>> .uni-switch-input {
		background-color: #007aff !important;
		border-color: #007aff !important;
		color: #ffffff !important;
		border-color: #007aff !important;
	}
</style>

加上>>>后,上面代码渲染的css代码如下,这样我们自己写的css就生效了

uni-switch.blue-checked[data-v-82079b42] .uni-switch-input {
	background-color: #007aff !important;
	border-color: #007aff !important;
	color: #ffffff !important;
	border-color: #007aff !important;
}

2、在全局app.vue引入样式文件或写在style中,app.vue默认没有开启scoped,不会生成属性data-v-xxxxxx

Logo

前往低代码交流专区

更多推荐