在父組件中給子組件添加類名,子組件的樣式由父組件決定
由于"微信小程序"存在【樣式隔離機制】,且默認設置為isolated(啟用樣式隔離),因此這里給出以下兩種解決方案:
// 小程序編譯機制
1. 當 <style scoped> 存在時,uni-app 會通過 ?添加屬性選擇器? 實現樣式隔離(如 [data-v-hash])。
但小程序編譯后,自定義組件無法添加此類屬性,也就無法命中元素2. 非 scoped 的 <style> 標簽不會添加隔離屬性// H5無論是否添加"scoped"屬性,樣式表現都一致
H5 的渲染基于瀏覽器,page 會被解析為 <div> 或 <body> 元素。即使使用 <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"樣式才生效。
注意: 父子組件<style>標簽不能添加"scoped"屬性
,可把這個樣式單獨放進 <style>
缺點:
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;}
文檔地址