Skip to content

Naive UI、UnoCSS 与主题

Forge 前端使用 Naive UI 组件库 + UnoCSS 原子化 CSS。你需要了解两者的协作方式和主题定制。

Naive UI

组件使用

Naive UI 组件全局注册,直接使用:

vue
<template>
  <NButton type="primary" @click="handleSave">保存</NButton>
  <NInput v-model:value="form.name" placeholder="请输入名称" />
  <NSelect v-model:value="form.type" :options="typeOptions" />
  <NDataTable :columns="columns" :data="tableData" />
</template>

按需引入消息 API

useMessageuseDialog 需要在 setup 中调用:

vue
<script setup>
import { useMessage, useDialog } from 'naive-ui'

const message = useMessage()
const dialog = useDialog()

function handleSave() {
  message.success('保存成功')
}

function handleDelete() {
  dialog.warning({
    title: '确认删除',
    content: '删除后不可恢复,确定删除?',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      message.success('删除成功')
    }
  })
}
</script>

在非 setup 环境使用 window.$message

javascript
// 已全局挂载
window.$message.success('操作成功')
window.$message.error('操作失败')

UnoCSS

原子化类

vue
<template>
  <div class="p-4 flex items-center justify-between">
    <span class="text-lg font-bold text-primary">标题</span>
    <NButton class="ml-2">按钮</NButton>
  </div>
</template>

常用类名

类名说明
p-4padding: 1rem
m-2margin: 0.5rem
flexdisplay: flex
items-centeralign-items: center
justify-betweenjustify-content: space-between
text-lgfont-size: 1.125rem
font-boldfont-weight: 700

语义化颜色

类名颜色场景
text-primary编辑、查看
text-info灰蓝详情、统计
text-warning刷新缓存、重置
text-error删除
text-success绿启用、发布

操作按钮样式

vue
<template>
  <div class="flex gap-2">
    <a class="text-primary cursor-pointer hover:text-primary-hover" @click="handleEdit">编辑</a>
    <a class="text-error cursor-pointer hover:text-error-hover" @click="handleDelete">删除</a>
  </div>
</template>

主题定制

Naive UI 主题覆盖

typescript
// src/config/theme.ts
import { defineThemeOverrides } from 'naive-ui'

export const themeOverrides = {
  common: {
    primaryColor: '#2080f0',
    primaryColorHover: '#4098fc',
    primaryColorPressed: '#1060c9',
    borderRadius: '4px'
  },
  Button: {
    textColorPrimary: '#fff'
  }
}

暗色模式

javascript
import { useAppStore } from '@/stores/app'

const appStore = useAppStore()

// 切换暗色模式
appStore.toggleTheme()

// 响应式获取主题
const isDark = computed(() => appStore.theme === 'dark')
vue
<template>
  <NConfigProvider :theme="isDark ? darkTheme : null">
    <App />
  </NConfigProvider>
</template>

UnoCSS 主题变量

scss
// src/styles/variables.scss
:root {
  --color-primary: #2080f0;
  --color-primary-hover: #4098fc;
  --color-error: #d03050;
  --color-success: #18a058;
  --color-warning: #f0a020;
}

样式规范

规则说明
优先使用 UnoCSS布局、间距、颜色用 UnoCSS 类
组件内样式用 scoped<style scoped lang="scss">
禁止使用 !important通过提升选择器优先级解决
操作按钮用语义化颜色text-primarytext-error

Forge Admin — 基于 Vue3 + Spring Boot 的企业级后台管理框架