VaporCSS 在UTS 用法参考
什么是 VaporCSS 注解式样式
VaporCSS 支持在 UTS 文件中使用特殊的注释标记来定义和使用元子化样式。这种用法称为注解式样式定义,通过 // @tui-autocss-include 注释标记,编译器会在编译阶段将注释代码块中的样式编译为对应的 CSS 类。
基本用法
typescript
// @tui-autocss-include
const themeiconLineHeightClass: UTSJSONObject = {
mini: 'slh-12px',
small: 'slh-14px',
medium: 'slh-16px',
large: 'slh-18px'
}
// @tui-autocss-include
let state_sty: Array<any | null> = check_state.value
? [`${typeMerge.value == '' ? 'bw-1px bc-#ccc!' : 'bw-0px'}`, extendsBackgroundColor.value, props.activeClass, CheckGroupAttrs?.activeClass]
: ['bw-1px bc-#ccc!', props.inactiveClass, CheckGroupAttrs?.inactiveClass]
// @tui-autocss-include
let sty = 'bs '
// @tui-autocss-include
const mr = `mr-14 `
if (modeMerge.value == 'checkbox') sty += mr
// @tui-autocss-include
const box = `${themeBoxSise.value} r-10 ${extendsBorder.value}`工作原理
- 注解标记:在 UTS 文件中使用
// @tui-autocss-include注释标记样式定义代码块 - 编译处理:编译器在编译阶段扫描这些注释标记
- 样式提取:提取注释代码块中的样式类名
- CSS 生成:将提取的样式类名编译为对应的 CSS 规则
- 类名使用:在运行时直接使用这些类名
优势
- 类型安全:在 TypeScript 环境中使用,享受类型检查
- 动态生成:可以根据条件动态生成样式类
- 编译优化:只生成实际使用的样式,减小包体积
- 代码组织:将样式逻辑与业务逻辑放在一起,提高代码可读性
适用场景
- 组件开发:在自定义组件中定义样式变量
- 动态样式:根据不同状态生成不同的样式组合
- 主题适配:结合主题系统实现动态样式切换
高级用法
条件样式
typescript
// @tui-autocss-include
const getButtonStyle = (size: string, type: string) => {
const sizeMap = {
small: 'px-2 py-1',
medium: 'px-4 py-2',
large: 'px-6 py-3'
}
const typeMap = {
primary: 'bg-primary text-white',
secondary: 'bg-gray-200 text-gray-800',
danger: 'bg-red-500 text-white'
}
return `${sizeMap[size]} ${typeMap[type]} rounded-md`
}样式组合
typescript
// @tui-autocss-include
const baseStyle = 'flex items-center'
// @tui-autocss-include
const buttonStyle = (variant: string) => {
const variants = {
primary: 'bg-primary text-white',
outline: 'border border-primary text-primary'
}
return `${baseStyle} ${variants[variant]} px-4 py-2 rounded-md`
}最佳实践
- 合理组织:将相关的样式定义放在一起,便于维护
- 类型定义:使用 TypeScript 类型系统确保样式类的正确性
- 注释说明:为复杂的样式逻辑添加注释,提高代码可读性
- 性能优化:避免在运行时频繁生成样式类,尽量在初始化时计算
- 命名规范:使用语义化的变量名,提高代码可维护性
通过这种注解式的样式定义方法,您可以在 UTS 中更加灵活地使用 VaporCSS,实现更加复杂的样式逻辑,为您的 UniApp X 应用提供更加优雅的样式解决方案。