//Card.vue <template> <div class="card"> <img class="card-img" :src="img" /> <p class="card-desc">{{ desc }}</p> </div> </template> <style lang="scss" scoped> .card { // 这些以"--"开头的变量就是我们开放可自定义的样式属性了,可以在组件使用文档中明确开放 //卡片根元素样式 --width: 150px; --height: auto; --border-size: 1px; --border-color: #ccc; --border-radius: 5px; --bg: #eee; // 图片可定样式 --img-width: 130px; --img-height: 130px; --img-radius: 50%; // 卡片描述样式 --desc-size: 16px; --desc-line-height: 32px; --desc-color: #333; height: var(--height; width: var(--width; border: var(--border-size solid var(--border-color; border-radius: var(--border-radius; background: var(--bg; padding: 10px; &-img { width: var(--img-width; height: var(--img-height; border-radius: var(--img-radius; overflow: hidden; } &-desc { font-size: var(--desc-size; color: var(--desc-color; line-height: var(--desc-line-height; text-align: center; } } </style>
//demo.vue <template> <div > <Card desc="我是默认的样式我是默认的样式我是默认的样式" :img="img" /> <Card class="card_1" desc="自定义样式,子元素图片变小了" :img="img" /> <Card class="card_2" desc="自定义样式,圆角没了,描述字变小了,高度高了" :img="img" /> </div> </template> <script>...</script> <style lang="scss" scoped> .card_1 { --width: 100px; --height: 200px; --border-radius: 20px; --img-width: 80px; --img-height: 50px; --img-radius: 10px; --desc-color: #f00; --desc-size: 12px; --desc-line-height: 21px; } .card_2 { --height: 300px; --border-radius: 0px; --bg: #fff; --img-radius: 50px; --desc-size: 14px; --desc-line-height: 21px; } </style>
//demo.vue <template> <card desc="我是默认的样式我是默认的样式" :img="img" :style="hoverStyle" @mouseout="hoverStyle = {}" @mouseover="handleHover" /> </template> <script setup> let hoverStyle = ref({}; const handleHover = ( => { hoverStyle.value = { '--bg': '#f0f', '--width': '180px' }; }; </script>
//card.vue <template> <div class="card" :style="style"> {{ width }} <img class="card-img" :src="img" /> <p class="card-desc">{{ desc }}</p> </div> </template> <script setup> const $props = defineProps({ img: { type: String, default: '', }, desc: { type: String, default: '', }, style: { type: Object, default: ( => ({}, }, }; //假如你在js中需要用到宽度 let width = computed(( => { return parseInt($props.style['--width'] || 150; }; </script> <style lang="scss" scoped> .card{ ... //假如你有个子级元素需要基于宽度计算 .item{ width: calc(var(--width - 100 } ... } </style>
但是这种实现有命名空间的问题
//比如这样 .ch-card{ --ch-card-width:100px; --ch-card-height:100px; }