对于前端开发者来说,或多或少的都想拥有一个属于自己的组件库,下面我们就来一起看看如何开发一个属于自己的组件库,满足自己的小愿望。
我们知道一个组件库最基础的组件就是button,他没有过多的交互,就是一些样式的堆叠,但是开发出一个市面上组件库完整功能的按钮组件也有很多需要注意的事项,下面我们来分析一下吧。
具体button组件有哪些属性,可以参考element-plus
项目搭建
我们直接使用vuejs/create-vue: 🛠️ The recommended way to start a Vite-powered Vue project (github.com))即可。
vite结合eslint插件,做项目构建时eslint配置。但是安装完vite-plugin-eslint
后,引入到vite配置文件报错,下面是解决办法。
Typescript types are not properly exported · Issue #74 · gxmari007/vite-plugin-eslint (github.com)
就是在vite-plugin-eslint
的package.json中将类型声明文件导出"types": "./dist/index.d.ts"
打包就会出现提示。
如果没有安装这个vite插件,打包时将不会被提示。
组件库样式设计
其实前端有很多css预处理器(sass, less, stylus),但是这里我们直接使用postcss
来进行样式处理。他并没有向其他预处理器一样具有很多功能,它类似于一个平台,我们使用对应的功能需要安装对应的插件,他是渐进式的。并且vite原生支持postcss插件。
并且css原生支持定义变量,css选择器嵌套语法(主流浏览器都支持了)
对于循环语法,我们可以使用postcss-each
, 混入可以使用postcss-mixins
等等
组件库主题色选取
button组件属性
type
button按钮的类型,即通过不同颜色进行区分。
plan
是否为朴素按钮,即无背景色。
round
是否是圆角按钮。
circle
是否是原型按钮,一般都是通过图标最为内容。
size
button的大小。
disabled
是否禁用按钮。
icon
按钮显示的图标。
loading
是否为加载中状态。
button原生属性
我们在使用一些原生标签时,一定要考虑到自身的属性,所以还需要加上nativeType
, autofocus
export type ButtonType = 'primary' | 'success' | 'warning' | 'danger' | 'info'
export type ButtonSize = 'small' | 'medium' | 'large'
export type NativeType = 'button' | 'submit' | 'reset'
export interface ButtonProps {
type?: ButtonType
size?: ButtonSize
plain?: boolean
round?: boolean
circle?: boolean
disabled?: boolean
nativeType?: NativeType
autofocus?: boolean
loading?: boolean
icon?: string
}
对于button组件来说就是通过上面的属性来配置不同的class类名设置样式而已。
button模板
就是通过动态添加class来实现的。
<button
ref="_ref"
class="hm-button"
:class="{
[`hm-button--${type}`]: type,
[`hm-button--${size}`]: size,
'is-plain': plain,
'is-round': round,
'is-circle': circle,
'is-disabled': disabled
}"
:disabled="disabled || loading"
:type="nativeType"
:autofocus="autofocus"
>
<span>
<slot />
</span>
</button>
具体代码请访问这里,后续组件的开发会持续更新到对应的分支。
往期年度总结
往期文章
- 展示大量数据节点(tree),引发的一次性能排查
- ts装饰器的那点东西
- 这是你所知道的ts类型断言和类型守卫吗?
- TypeScript官网内容解读
- 经常使用ts的你,知道这些内容?
- 你有了解过原生css的scope?
- 现在比较常用的移动端调试你知道哪些?
- 众多跨标签页通信方式,你知道哪些?(二)
- 众多跨标签页通信方式,你知道哪些?
- 反调试吗?如何监听devtools的打开与关闭
- 因为原生,选择一家公司(前端如何防笔试作弊)
- 结合开发,带你熟悉package.json与tsconfig.json配置
- 如何优雅的在项目中使用echarts
- 如何优雅的做项目国际化
- 近三个月的排错,原来的憧憬消失喽
- 带你从0开始了解vue3核心(运行时)
- 带你从0开始了解vue3核心(computed, watch)
- 带你从0开始了解vue3核心(响应式)
- 3w+字的后台管理通用功能解决方案送给你
- 入职之前,狂补技术,4w字的前端技术解决方案送给你(vue3 + vite )