uniapp vue 样式穿透

2,436 阅读1分钟
  1. 需求: A组件已经被很多个地方使用,B页面中调用A组件,A组件的颜色需要在B页面中有特定的颜色,但我不可能直接修改A组件,因为这样会影像其他页面,这时候就需要样式穿透,通过B页面中的样式穿透操作修改A组件的颜色(样式)

  2. 样式穿透的方式:

    /deep/ 使用场景:项目中用到了预处理器 scss 、sass、less 的时候,vue-cli3可能会导致编译报错 >>>操作符 使用场景:项目使用的css样式并且没有使用预处理器 scss 、sass、less
    ::v-deep 使用场景:1.在有预处理器 scss 、sass、less的时候 2.在使用vue-cli3的时候也建议使用。

  3. 演示 接下来使用/deep/方式演示

    test1修改test2.vue和test3.vue的样式
    test1.vue如下:

<template>
	<view>
		<a-d class="a-d"></a-d>
	</view>
</template>
<script>
	import a from "@/components/a.vue";
	export default {
		components: {
			"a-d": a
		}
	}
</script>
<style lang="scss" scoped>
       //根据类名修改样式
	.a-d /deep/ .a{
		color: red;
		.b{
			color: blue;
		}
	}
</style>

test2.vue如下

<template>
	<view class="a" id="r">
		<text>a</text>
		<b-d class="b-d"></b-d>
	</view>
</template>

<script>
	import b from "@/pages/test/test3.vue";
	export default {
		components:{
			"b-d": b
		},
		name:"a"
	}
</script>

test3.vue如下

<template>
	<view class="b">
		<text>b</text>
	</view>
</template>
<script>
	export default {
		name:"b",
	}
</script>
  1. 参考文章: UniApp 组件内修改组件内的组件的样式,穿透组件中的组件样式_重庆鱼白科技的博客-CSDN博客

  2. 遇到的问题

组件命名方式影响穿透的生效: 像AbD、aD的组件命名都不能使穿透生效,a-d可以使穿透生效

	<view>
		<AbD class="a-d"></AbD>
	</view>
</template>
<script>
	import a from "@/pages/test/test2.vue";
	export default {
		components: {
			"AbD": a  //命名方式AbD不能使穿透生效
		}
	}
</script>
<style lang="scss" scoped>
	.AbD  /deep/ .a{
		color: red;
		.b{
			color: blue;
		}
	}
	// 
</style>
<template>
	<view>
		<aD class="a-d"></aD>
	</view>
</template>
<script>
	import a from "@/pages/test/test2.vue";
	export default {
		components: {
			"aD": a  //命名方式aD不能使穿透生效
		}
	}
</script>
<style lang="scss" scoped>
	.aD  /deep/ .a{
		color: red;
		.b{
			color: blue;
		}
	}
	// 
</style>