跳转到内容

使用 Naive UI 组件

一个 Vue 3 组件库,比较完整,主题可调,使用 TypeScript,速度快。

安装

sh
npm install -D naive-ui
sh
yarn add -D naive-ui
sh
pnpm add -D naive-ui
sh
bun add -D naive-ui

配置

App Config
ts
// .vitepress/config.mts
import { defineConfig } from 'vitepress';

export default defineConfig({
  vite: {
    ssr: { 
      noExternal: ['naive-ui', 'date-fns', 'vueuc', 'css-render'], 
    }, 
  },
});
Theme Config
ts
// .vitepress/theme/index.ts
import type { Theme, useData } from 'vitepress'; 
import DefaultTheme from 'vitepress/theme';

import naive from 'naive-ui'; 
import { darkTheme, zhCN, dateZhCN, NConfigProvider, NMessageProvider } from 'naive-ui'; 

export default {
  extends: DefaultTheme,
  Layout: () => {
    return h(DefaultTheme.Layout, null, { 
    }); 

    const { isDark } = useData(); 
    const theme = isDark.value ? darkTheme : null; 
    const locale = zhCN; 
    const dateLocale = dateZhCN; 
    return h(NConfigProvider, { theme, locale, dateLocale }, { 
      default: () => h(NMessageProvider, {}, { 
        default: () => h(DefaultTheme.Layout) 
      }) 
    }); 
  },
  enhanceApp({ app, router, siteData }) {
    app.use(naive); 
  },
} satisfies Theme;

使用

直接使用

markdown
<n-space>
  <n-button>Default</n-button>
  <n-button type="tertiary"> Tertiary </n-button>
  <n-button type="primary"> Primary </n-button>
  <n-button type="info"> Info </n-button>
  <n-button type="success"> Success </n-button>
  <n-button type="warning"> Warning </n-button>
  <n-button type="error"> Error </n-button>
</n-space>

自定义组件

1. 定义组件

html
<!-- ../components/NaiveModal.vue -->
<template>
  <n-space>
    <n-button @click="showModal = true"> 点击我, 打开对话框 </n-button>
  </n-space>
  <n-modal v-model:show="showModal">
    <n-card title="提示信息" style="width: 480px;">
      模态框的基础用法,你可以把任何东西放进去,比如一个卡片。
    </n-card>
  </n-modal>
</template>

<script setup>
import { ref } from 'vue';

const showModal = ref(false);
</script>
html
<!-- ../components/NaiveMessage.vue -->
<template>
  <n-space>
    <n-button type="primary" @click="handleClick">  点击我, 查看消息 </n-button>
  </n-space>
</template>

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

const message = useMessage();

const handleClick = () => {
  message.success('你有新的消息,请注意查收!');
}
</script>

2. 使用组件

markdown
<script setup>
import NaiveModal from '../components/NaiveModal.vue';
import NaiveMessage from '../components/NaiveMessage.vue';
</script>

<n-space vertical>
  <NaiveModal />
  <NaiveMessage />
</n-space>

基于 MIT 许可发布