Skip to content

主题属性

能够应用自定义样式的属性。在进入组件文档前,需要了解主题属性特性。

基础用法

组件库中的每个组件在实现时都继承了主题属性 theme,即每个组件都拥有 theme 这个 prop,通过 theme 属性可以实现对组件元素的样式自定义。

<template>
    <nue-button theme="custom">按钮 Button</nue-button>
</template>

<style scoped>
.nue-button--custom {
    --custom-color: 0 72.22% 50.59%;

    color: white;
    background-color: hsl(var(--custom-color));
    border-color: transparent;

    &:hover {
        background-color: hsl(var(--custom-color) / 0.9);
    }

    &:active {
        background-color: hsl(var(--custom-color) / 0.7);
    }
}
</style>

从上面的使用示例可以看到 theme 属性的基础应用逻辑,通过传入一个有标识性的字符串,在组件渲染时会为组件元素挂上一个主题类名(如 nue-button--custom)。这样我们就可以为这个类名编写样式片段,通过复写原有样式实现样式自定义。

可能会觉得 theme 属性的存在和原有的 class 属性在应用上别无二致,这里提出 theme 属性的两个设计原因:一是避免过长的 class 字符串;二是避免样式冲突或重复的前缀编写。若不曾考虑这两个设计原因,则可以使用 class 属性应用自定义样式,theme 作为补充。

同时使用多个主题

属性 theme 能够同时接收字符串和数组类型。数组类型应用多个主题即传入有主题标识字符串组成的数组即可,在渲染时会分别挂上对应的类名,如 ['custom1', 'custom2'] 转换为 'nue-xxx--custom1 nue-xxx--custom2' 两个类名;字符串类型应用多个主题则在编写上通过逗号隔开,如 custom1,custom2,转换结果同上。

<template>
    <nue-div>
        <nue-button theme="custom1,custom2">按钮 Button</nue-button>
        <nue-button :theme="['custom1', 'custom2']">按钮 Button</nue-button>
    </nue-div>
</template>

<style scoped>
.nue-button--custom1 {
    --custom-color: 0 72.22% 50.59%;

    color: white;
    background-color: hsl(var(--custom-color));
    border-color: transparent;
}

.nue-button--custom2 {
    &:hover {
        background-color: hsl(var(--custom-color) / 0.9);
    }

    &:active {
        background-color: hsl(var(--custom-color) / 0.7);
    }
}
</style>

动态应用主题

除了通过字符串和字符串数组,还支持通过对象的形式应用主题,对象类型的应用形式多数用于动态应用。

动态应用指的是主题的应用会根据外部布尔变量决定,当变量为真值则应用,反之不应用。

<template>
    <nue-button :theme="{ custom: true, round: isRounded }" @click="isRounded = !isRounded">
        点击{{ isRounded ? '取消' : '应用' }} Round 主题
    </nue-button>
</template>

<script lang="ts" setup>
import { ref } from 'vue';

const isRounded = ref(false);
</script>

<style scoped>
.nue-button--custom {
    --custom-color: 0 72.22% 50.59%;

    color: white;
    background-color: hsl(var(--custom-color));
    border-color: transparent;
    transition: none;

    &:hover {
        background-color: hsl(var(--custom-color) / 0.9);
    }

    &:active {
        background-color: hsl(var(--custom-color) / 0.7);
    }
}

.nue-button--round {
    border-radius: 99px;
}
</style>

Released under the MIT License.