关于NaiveUI是最好的组件库这件事和NaiveUI的简单使用

4,462 阅读2分钟

前言

前几天有小伙伴留言Naive UI是世界上最好的组件库么?于是我就去浅析一下Vue 3组件库 Naive UI,看上去很不错。于是我今天来体验体验!

1.png

创建项目

首先我们来创建一个vue3项目,我这里使用vite来创建:

$ npm init vite-app naiveui-demo
$ cd naiveui-demo
$ npm install
$ npm run dev

你也可以选择其他你喜欢的方式

NaiveUI介绍

Naive UI由图森未来开源的一个Vue3的组件库(目前仅支持Vue3),该项目具有以下几个特点:

  • 比较完整
    有超过70 个组件,特点是它们全都可以treeshaking

  • 主题可调
    提供了一个使用 Typescript构建的先进的类型安全主题系统。你只需要提供一个样式覆盖的对象。不用 lesssasscss变量,也不用webpackloaders

  • 使用 Typescript
    Naive UI全量使用Typescript编写,和你的Typescript 项目无缝衔接。你不需要导入任何 CSS 就能让组件正常工作

  • 不算太慢
    selecttreetransfertablecascader 都可以用虚拟列表

安装

使用 npm 安装。

npm i -D naive-ui

使用方式

我们先在项目的src\components目录下新建一个组件:Naiveui.vue

接着,我们可以选择直接引入或全局安装。先使用第一种方式直接引入,也是推荐的一种方式

//src\components\Naiveui.vue
<template>
  <n-button>naive-ui</n-button>
</template>


<script>
import { NButton } from 'naive-ui'




export default {
components: {
NButton
}
}
</script>

export default { components: { NButton } } </script>

然后将我们的组件引入App.vue中即可


//src\App.vue
<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <HelloWorld msg="Hello Vue 3.0 + Vite" />
  <Naiveui />
</template>


<script>
import HelloWorld from './components/HelloWorld.vue'
import Naiveui from './components/Naiveui.vue'




export default {
name: 'App',
components: {
HelloWorld,
Naiveui
}
}
</script>

export default { name: 'App', components: { HelloWorld, Naiveui } } </script>

于是我们的按钮就会出现在页面中,如下

动画1.gif

我们也可以全局引入,但会失去 tree-shaking的能力,打包有冗余代码。

//main.js
import { createApp } from 'vue'
import App from './App.vue'
import './index.css'
import naive from 'naive-ui'


const app = createApp(App)
app.use(naive)
app.mount('#app')

const app = createApp(App) app.use(naive) app.mount('#app')

安装后,你可以在SFC中使用全部组件,这样就不用一个一个导入了,为了方便测试

使用更多组件

我们上面配置了全局安装,那如何使用更多组件。使用过程也很简单,即复制、粘贴、页面展示。
如下

动画2.gif

展示效果

由于组件太多,这里随机截取几张官网的图来展示一下

image.png
image.png
image.png
image.png
image.png
image.png
image.png
image.png
image.png
image.png

更多详情可以移步官网:www.naiveui.com/zh-CN/os-th…

总结

总体来说第一印象是不错的,单对于用习惯了element的我来说,我选择element