uniapp(微信小程序)>关于父子组件的样式传递问题(自定义组件样式穿透)
由于"微信小程序"存在【样式隔离机制】,且默认设置为isolated(启用样式隔离),因此这里给出以下两种解决方案:
注意: 这2种方案父子组件<style>标签不能添加"scoped"
1.CSS变量穿透(推荐: 此方案不受样式隔离限制,适配所有端)
缺点:所需的CSS属性要逐个设置变量,自定义组件逐个接收
<!-- 父组件 Parent.vue -->
<template><Child class="parent-style"></Child>
</template><style>
.parent-style {/* 定义 CSS 变量 */--img-width: 262rpx;--img-height: 120rpx;--img-border-radius: 16rpx 16rpx 0 0;
}
</style>
<!-- 子组件 Child.vue -->
<template><view class="child-box"><image class="child-img" /></view>
</template> <style>
.child-img {width: var(--img-width);height: var(--img-height);border-radius: var(--img-border-radius);
}
</style>
2.配置隔离模式(不太推荐)
styleIsolation是"微信小程序"特有的样式隔离配置项,具体有哪些属性值在最下方图中。
在测试中,可能是–组件层级–的缘故,只有配置了"shared"、"page-shared"样式才生效。
缺点:
1.易造成样式污染,即父子组件若存在同类名会相互干扰样式,其他设置了"shared"的组件可能也会受到污染
2.子组件元素层级要定位明确(要更改样式的元素),否则整个自定义组件样式都要受到父组件的影响
2.1 选项式api:
<!-- 父组件 Parent.vue -->
export default {options:{styleIsolation: 'shared',},data() {return {}}
}
2.2 组合式api:
<!-- 父组件 Parent.vue -->
<script setup>
import { defineOptions } from 'vue';
defineOptions({options: {styleIsolation: 'shared' }
});
</script>
<!-- 父组件 Parent.vue(.child-img对应的是子组件中要修改的元素类名) -->
.child-img {width: 298rpx;height: 186rpx;border-radius: 16rpx;}
文档地址