从0搭建vue3组件库: Input组件
本篇文章将为我们的组件库添加一个新成员:Input组件。其中Input组件要实现的功能有:
基础用法禁用状态尺寸大小输入长度可清空密码框带Icon的输入框文本域自适应文本高度的文本域复合型输入框
每个功能的实现代码都做了精简,方便大家快速定位到核心逻辑,接下来就开始对这些功能进行一一的实现。
基础用法
首先先新建一个input.vue文件,然后写入一个最基本的input输入框
<template>
<div class="k-input">
<input class="k-input__inner" />
</div>
</template>
然后在我们的 vue 项目examples下的app.vue引入Input组件
<template>
<div class="Shake-demo">
<Input />
</div>
</template>
<script lang="ts" setup>
import { Input } from "kitty-ui";
</script>
此时页面上便出现了原生的输入框,所以需要对这个输入框进行样式的添加,在input.vue同级新建style/index.less,Input样式便写在这里
.k-input {
font-size: 14px;
display: inline-block;
position: relative;
.k-input__inner {
background-color: #fff;
border-radius: 4px;
border: 1px solid #dcdfe6;
box-sizing: border-box;
color: #606266;
display: inline-block;
font-size: inherit;
height: 40px;
line-height: 40px;
outline: none;
padding: 0 15px;
width: 100%;
&::placeholder {
color: #c2c2ca;
}
&:hover {
border: 1px solid #c0c4cc;
}
&:focus {
border: 1px solid #409eff;
}
}
}
接下来要实现Input组件的核心功能:双向数据绑定。当我们在 vue 中使用input输入框的时候,我们可以直接使用v-model来实现双向数据绑定,v-model其实就是value @input结合的语法糖。而在 vue3 组件中使用v-model则表示的是modelValue @update:modelValue的语法糖。比如Input组件为例
<Input v-model="tel" />
其实就是
<Input :modelValue="tel" @update:modelValue="tel = $event" />
所以在input.vue中我们就可以根据这个来实现Input组件的双向数据绑定,这里我们使用setup语法
<template>
<div class="k-input">
<input
class="k-input__inner"
:value="inputProps.modelValue"
@input="changeInputVal"
/>
</div>
</template>
<script lang="ts" setup>
//组件命名
defineOptions({
name: "k-input",
});
//组件接收的值类型
type InputProps = {
modelValue?: string | number;
};
//组件发送事件类型
type InputEmits = {
(e: "update:modelValue", value: string): void;
};
//withDefaults可以为props添加默认值等
const inputProps = withDefaults(defineProps<InputProps>(), {
modelValue: "",
});
const inputEmits = defineEmits<InputEmits>();
const changeInputVal = (event: Event) => {
inputEmits("update:modelValue", (event.target as HTMLInputElement).value);
};
</script>
到这里基础用法就完成了,接下来开始实现禁用状态
禁用状态
这个比较简单,只要根据props的disabled来赋予禁用类名即可
<template>
<div class="k-input" :class="styleClass">
<input
class="k-input__inner"
:value="inputProps.modelValue"
@input="changeInputVal"
:disabled="inputProps.disabled"
/>
</div>
</template>
<script lang="ts" setup>
//...
type InputProps = {
modelValue?: string | number;
disabled?: boolean;
};
//...
//根据props更改类名
const styleClass = computed(() => {
return {
"is-disabled": inputProps.disabled,
};
});
</script>
然后给is-disabled写些样式
//...
.k-input.is-disabled {
.k-input__inner {
background-color: #f5f7fa;
border-color: #e4e7ed;
color: #c0c4cc;
cursor: not-allowed;
&::placeholder {
color: #c3c4cc;
}
}
}
尺寸
按钮尺寸包括medium,small,mini,不传则是默认尺寸。同样的根据props的size来赋予不同类名
const styleClass = computed(() => {
return {
"is-disabled": inputProps.disabled,
[`k-input--${inputProps.size}`]: inputProps.size,
};
});
然后写这三个类名的不同样式
//...
.k-input.k-input--medium {
.k-input__inner {
height: 36px;
&::placeholder {
font-size: 15px;
}
}
}
.k-input.k-input--small {
.k-input__inner {
height: 32px;
&::placeholder {
font-size: 14px;
}
}
}
.k-input.k-input--mini {
.k-input__inner {
height: 28px;
&::placeholder {
font-size: 13px;
}
}
}
继承原生 input 属性
原生的input有type,placeholder等属性,这里可以使用 vue3 中的useAttrs来实现props穿透.子组件可以通过v-bind将props绑定
<template>
<div class="k-input" :class="styleClass">
<input
class="k-input__inner"
:value="inputProps.modelValue"
@input="changeInputVal"
:disabled="inputProps.disabled"
v-bind="attrs"
/>
</div>
</template>
<script lang="ts" setup>
//...
const attrs = useAttrs();
</script>
可清空
通过clearable属性、Input的值是否为空以及是否鼠标是否移入来判断是否需要显示可清空图标。图标则使用组件库的Icon组件
<template>
<div
class="k-input"
@mouseenter="isEnter = true"
@mouseleave="isEnter = false"
:class="styleClass"
>
<input
class="k-input__inner"
:disabled="inputProps.disabled"
v-bind="attrs"
:value="inputProps.modelValue"
@input="changeInputVal"
/>
<div
@click="clearValue"
v-if="inputProps.clearable && isClearAbled"
v-show="isFoucs"
class="k-input__suffix"
>
<Icon name="error" />
</div>
</div>
</template>
<script setup lang="ts">
//...
import Icon from "../icon/index";
//...
//双向数据绑定&接收属性
type InputProps = {
modelValue?: string | number;
disabled?: boolean;
size?: string;
clearable?: boolean;
};
//...
const isClearAbled = ref(false);
const changeInputVal = (event: Event) => {
//可清除clearable
(event.target as HTMLInputElement).value
? (isClearAbled.value = true)
: (isClearAbled.value = false);
inputEmits("update:modelValue", (event.target as HTMLInputElement).value);
};
//清除input value
const isEnter = ref(true);
const clearValue = () => {
inputEmits("update:modelValue", "");
};
</script>
清除图标部分 css 样式
.k-input__suffix {
position: absolute;
right: 10px;
height: 100%;
top: 0;
display: flex;
align-items: center;
cursor: pointer;
color: #c0c4cc;
}
密码框 show-password
通过传入show-password属性可以得到一个可切换显示隐藏的密码框。这里要注意的是如果传了clearable则不会显示切换显示隐藏的图标
<template>
<div
class="k-input"
@mouseenter="isEnter = true"
@mouseleave="isEnter = false"
:class="styleClass"
>
<input
ref="ipt"
class="k-input__inner"
:disabled="inputProps.disabled"
v-bind="attrs"
:value="inputProps.modelValue"
@input="changeInputVal"
/>
<div class="k-input__suffix" v-show="isShowEye">
<Icon @click="changeType" :name="eyeIcon" />
</div>
</div>
</template>
<script setup lang="ts">
//...
const attrs = useAttrs();
//...
//显示隐藏密码框 showPassword
const ipt = ref();
Promise.resolve().then(() => {
if (inputProps.showPassword) {
ipt.value.type = "password";
}
});
const eyeIcon = ref("browse");
const isShowEye = computed(() => {
return (
inputProps.showPassword && inputProps.modelValue && !inputProps.clearable
);
});
const changeType = () => {
if (ipt.value.type === "password") {
eyeIcon.value = "eye-close";
ipt.value.type = attrs.type || "text";
return;
}
ipt.value.type = "password";
eyeIcon.value = "browse";
};
</script>
这里是通过获取
input元素,然后通过它的type属性进行切换,其中browse和eye-close分别是Icon组件中眼睛开与闭,效果如下
带 Icon 的输入框
通过prefix-icon和suffix-icon 属性可以为Input组件添加首尾图标。
可以通过计算属性判断出是否显示首尾图标,防止和前面的clearable和show-password冲突.这里代码做了
<template>
<div class="k-input">
<input
ref="ipt"
class="k-input__inner"
:class="{ ['k-input--prefix']: isShowPrefixIcon }"
:disabled="inputProps.disabled"
v-bind="attrs"
:value="inputProps.modelValue"
@input="changeInputVal"
/>
<div class="k-input__prefix" v-if="isShowPrefixIcon">
<Icon :name="inputProps.prefixIcon" />
</div>
<div class="k-input__suffix no-cursor" v-if="isShowSuffixIcon">
<Icon :name="inputProps.suffixIcon" />
</div>
</div>
</template>
<script setup lang="ts">
//...
type InputProps = {
prefixIcon?: string;
suffixIcon?: string;
};
//...
//带Icon输入框
const isShowSuffixIcon = computed(() => {
return (
inputProps.suffixIcon && !inputProps.clearable && !inputProps.showPassword
);
});
const isShowPrefixIcon = computed(() => {
return inputProps.prefixIcon;
});
</script>
相关样式部分
.k-input__suffix,
.k-input__prefix {
position: absolute;
right: 10px;
height: 100%;
top: 0;
display: flex;
align-items: center;
cursor: pointer;
color: #c0c4cc;
font-size: 15px;
}
.no-cursor {
cursor: default;
}
.k-input--prefix.k-input__inner {
padding-left: 30px;
}
.k-input__prefix {
position: absolute;
width: 20px;
cursor: default;
left: 10px;
}
在app.vue中使用效果如下
<template>
<div class="input-demo">
<Input v-model="tel" suffixIcon="edit" placeholder="请输入内容" />
<Input v-model="tel" prefixIcon="edit" placeholder="请输入内容" />
</div>
</template>
<script lang="ts" setup>
import { Input } from "kitty-ui";
import { ref } from "vue";
const tel = ref("");
</script>
<style lang="less">
.input-demo {
width: 200px;
}
</style>
文本域
将type属性的值指定为textarea即可展示文本域模式。它绑定的事件以及属性和input基本一样
<template>
<div class="k-textarea" v-if="attrs.type === 'textarea'">
<textarea
class="k-textarea__inner"
:style="textareaStyle"
v-bind="attrs"
ref="textarea"
:value="inputProps.modelValue"
@input="changeInputVal"
/>
</div>
<div
v-else
class="k-input"
@mouseenter="isEnter = true"
@mouseleave="isEnter = false"
:class="styleClass"
>
...
</div>
</template>
样式基本也就是focus,hover改变 border 颜色
.k-textarea {
width: 100%;
.k-textarea__inner {
display: block;
padding: 5px 15px;
line-height: 1.5;
box-sizing: border-box;
width: 100%;
font-size: inherit;
color: #606266;
background-color: #fff;
background-image: none;
border: 1px solid #dcdfe6;
border-radius: 4px;
&::placeholder {
color: #c2c2ca;
}
&:hover {
border: 1px solid #c0c4cc;
}
&:focus {
outline: none;
border: 1px solid #409eff;
}
}
}
可自适应高度文本域
组件可以通过接收autosize属性来开启自适应高度,同时autosize也可以传对象形式来指定最小和最大行高
type AutosizeObj = {
minRows?: number
maxRows?: number
}
type InputProps = {
autosize?: boolean | AutosizeObj
}
具体实现原理是通过监听输入框值的变化来调整textarea的样式,其中用到了一些原生的方法譬如window.getComputedStyle(获取原生css对象),getPropertyValue(获取css属性值)等,所以原生js忘记的可以复习一下
...
const textareaStyle = ref<any>()
const textarea = shallowRef<HTMLTextAreaElement>()
watch(() => inputProps.modelValue, () => {
if (attrs.type === 'textarea' && inputProps.autosize) {
const minRows = isObject(inputProps.autosize) ? (inputProps.autosize as AutosizeObj).minRows : undefined
const maxRows = isObject(inputProps.autosize) ? (inputProps.autosize as AutosizeObj).maxRows : undefined
nextTick(() => {
textareaStyle.value = calcTextareaHeight(textarea.value!, minRows, maxRows)
})
}
}, { immediate: true })
其中calcTextareaHeight为
const isNumber = (val: any): boolean => {
return typeof val === 'number'
}
//隐藏的元素
let hiddenTextarea: HTMLTextAreaElement | undefined = undefined
//隐藏元素样式
const HIDDEN_STYLE = `
height:0 !important;
visibility:hidden !important;
overflow:hidden !important;
position:absolute !important;
z-index:-1000 !important;
top:0 !important;
right:0 !important;
`
const CONTEXT_STYLE = [
'letter-spacing',
'line-height',
'padding-top',
'padding-bottom',
'font-family',
'font-weight',
'font-size',
'text-rendering',
'text-transform',
'width',
'text-indent',
'padding-left',
'padding-right',
'border-width',
'box-sizing',
]
type NodeStyle = {
contextStyle: string
boxSizing: string
paddingSize: number
borderSize: number
}
type TextAreaHeight = {
height: string
minHeight?: string
}
function calculateNodeStyling(targetElement: Element): NodeStyle {
//获取实际textarea样式返回并赋值给隐藏的textarea
const style = window.getComputedStyle(targetElement)
const boxSizing = style.getPropertyValue('box-sizing')
const paddingSize =
Number.parseFloat(style.getPropertyValue('padding-bottom')) +
Number.parseFloat(style.getPropertyValue('padding-top'))
const borderSize =
Number.parseFloat(style.getPropertyValue('border-bottom-width')) +
Number.parseFloat(style.getPropertyValue('border-top-width'))
const contextStyle = CONTEXT_STYLE.map(
(name) => `${name}:${style.getPropertyValue(name)}`
).join(';')
return { contextStyle, paddingSize, borderSize, boxSizing }
}
export function calcTextareaHeight(
targetElement: HTMLTextAreaElement,
minRows = 1,
maxRows?: number
): TextAreaHeight {
if (!hiddenTextarea) {
//创建隐藏的textarea
hiddenTextarea = document.createElement('textarea')
document.body.appendChild(hiddenTextarea)
}
//给隐藏的teatarea赋予实际textarea的样式以及值(value)
const { paddingSize, borderSize, boxSizing, contextStyle } =
calculateNodeStyling(targetElement)
hiddenTextarea.setAttribute('style', `${contextStyle};${HIDDEN_STYLE}`)
hiddenTextarea.value = targetElement.value || targetElement.placeholder || ''
//隐藏textarea整个高度,包括内边距padding,border
let height = hiddenTextarea.scrollHeight
const result = {} as TextAreaHeight
//判断boxSizing,返回实际高度
if (boxSizing === 'border-box') {
height = height + borderSize
} else if (boxSizing === 'content-box') {
height = height - paddingSize
}
hiddenTextarea.value = ''
//计算单行高度
const singleRowHeight = hiddenTextarea.scrollHeight - paddingSize
if (isNumber(minRows)) {
let minHeight = singleRowHeight * minRows
if (boxSizing === 'border-box') {
minHeight = minHeight + paddingSize + borderSize
}
height = Math.max(minHeight, height)
result.minHeight = `${minHeight}px`
}
if (isNumber(maxRows)) {
let maxHeight = singleRowHeight * maxRows!
if (boxSizing === 'border-box') {
maxHeight = maxHeight + paddingSize + borderSize
}
height = Math.min(maxHeight, height)
}
result.height = `${height}px`
hiddenTextarea.parentNode?.removeChild(hiddenTextarea)
hiddenTextarea = undefined
return result
}
这里的逻辑稍微复杂一点,大致就是创建一个隐藏的
textarea,然后每次当输入框值发生变化时,将它的value赋值为组件的textarea的value,最后计算出这个隐藏的textarea的scrollHeight以及其它padding之类的值并作为高度返回赋值给组件中的textarea
最后在app.vue中使用
<template>
<div class="input-demo">
<Input
v-model="tel"
:autosize="{ minRows: 2 }"
type="textarea"
suffixIcon="edit"
placeholder="请输入内容"
/>
</div>
</template>
复合型输入框
我们可以使用复合型输入框来前置或者后置我们的元素,如下所示
这里我们借助 vue3 中的slot进行实现,其中用到了useSlots来判断用户使用了哪个插槽,从而展示不同样式
import { useSlots } from "vue";
//复合输入框
const slots = useSlots();
同时template中接收前后两个插槽
<template>
<div
class="k-input"
@mouseenter="isEnter = true"
@mouseleave="isEnter = false"
:class="styleClass"
>
<div class="k-input__prepend" v-if="slots.prepend">
<slot name="prepend"></slot>
</div>
<input
ref="ipt"
class="k-input__inner"
:class="inputStyle"
:disabled="inputProps.disabled"
v-bind="attrs"
:value="inputProps.modelValue"
@input="changeInputVal"
/>
<div class="k-input__append" v-if="slots.append">
<slot name="append"></slot>
</div>
</div>
</template>
<script setup lang="ts">
import { useSlots } from "vue";
const styleClass = computed(() => {
return {
["k-input-group k-input-prepend"]: slots.prepend,
["k-input-group k-input-append"]: slots.append,
};
});
//复合输入框
const slots = useSlots();
</script>
最后给两个插槽写上样式就实现了复合型输入框啦
.k-input.k-input-group.k-input-append,
.k-input.k-input-group.k-input-prepend {
line-height: normal;
display: inline-table;
width: 100%;
border-collapse: separate;
border-spacing: 0;
.k-input__inner {
border-radius: 0 4px 4px 0;
}
//复合输入框
.k-input__prepend,
.k-input__append {
background-color: #f5f7fa;
color: #909399;
vertical-align: middle;
display: table-cell;
position: relative;
border: 1px solid #dcdfe6;
border-radius: 4 0px 0px 4px;
padding: 0 20px;
width: 1px;
white-space: nowrap;
}
.k-input__append {
border-radius: 0 4px 4px 0px;
}
}
.k-input.k-input-group.k-input-append {
.k-input__inner {
border-top-right-radius: 0px;
border-bottom-right-radius: 0px;
}
}
在app.vue中使用
<template>
<div class="input-demo">
<Input v-model="tel" placeholder="请输入内容">
<template #prepend>
http://
</template>
</Input>
<Input v-model="tel" placeholder="请输入内容">
<template #append>
.com
</template>
</Input>
</div>
</template>
总结
一个看似简单的Input组件其实包含的内容还是很多的,做完之后会发现对自己很多地方都有提升和帮助。
如果你对vue3组件库开发也感兴趣的话可以关注我,组件库的所有实现细节都在以往文章里,包括环境搭建,自动打包发布,文档搭建,vitest单元测试等等。
如果这篇文章对你有所帮助动动指头点个赞吧~
源码地址
kitty-ui: 一个使用Vite+Ts搭建的Vue3组件库
从0搭建vue3组件库: Input组件的更多相关文章
- 从0搭建vue3组件库: 如何完整搭建一个前端脚手架?
相信大家在前端开发中都使用过很多前端脚手架,如vue-cli,create-vite,create-vue等:本篇文章将会为大家详细介绍这些前端脚手架是如何实现的,并且从零实现一个create-kit ...
- 从0搭建Vue3组件库:button组件
button组件几乎是每个组件库都有的:其实实现一个button组件是很简单的.本篇文章将带你一步一步的实现一个button组件.如果你想了解完整的组件库搭建,你可以先看使用Vite和TypeScri ...
- 从0搭建vue3组件库:Shake抖动组件
先看下效果 其实就是个抖动效果组件,实现起来也非常简单.之所以做这样一个组件是为了后面写Form表单的时候会用到它做一个规则校验,比如下面一个简单的登录页面,当点击登录会提示用户哪个信息没输入,当然这 ...
- 从0搭建vue3组件库:自动化发布、管理版本号、生成 changelog、tag
今天看到一篇文章中提到了一个好用的工具release-it.刚好可以用在我正在开发的vue3组件库.纸上得来终觉浅,绝知此事要躬行,说干就干,下面就介绍如何将release-it应用到实际项目中,让组 ...
- 08 - Vue3 UI Framework - Input 组件
接下来再做一个常用的组件 - input 组件 返回阅读列表点击 这里 需求分析 开始之前我们先做一个简单的需求分析 input 组件有两种类型,即 input 和 textarea 类型 当类型为 ...
- antd组件库BackTop组件设置动态背景图片的问题
有这么一个需求,利用antd组件库中的BackTop组件的逻辑,但是自己写样式. 我的目标样式是:有两张图片,一张是normal(正常情况),一张是hover(悬停情况). 这时候就要用到css的动画 ...
- Blazor Bootstrap 组件库语音组件介绍
Speech 语音识别与合成 通过麦克风语音采集转换为文字(STT),或者通过文字通过语音朗读出来(TTS) 本组件依赖于 BootstrapBlazor.AzureSpeech,使用本组件时需要引用 ...
- Vitepress搭建组件库文档(下)—— 组件 Demo
上文 <Vitepress搭建组件库文档(上)-- 基本配置>已经讨论了 vitepress 搭建组件库文档的基本配置,包括站点 Logo.名称.首页 home 布局.顶部导航.左侧导航等 ...
- 开箱即用 yyg-cli(脚手架工具):快速创建 vue3 组件库和vue3 全家桶项目
1 yyg-cli 是什么 yyg-cli 是优雅哥开发的快速创建 vue3 项目的脚手架.在 npm 上发布了两个月,11月1日进行了大升级,发布 1.1.0 版本:支持创建 vue3 全家桶项目和 ...
随机推荐
- 应用性能监控:SkyWalking
目录 SkyWalking 简介 SkyWalking 搭建 平台后端(Backend) 平台前端(UI) Java Agent(Java 应用监控) Java Agent 下载 Java 演练项目 ...
- Java自增自减运算
自增自减运算 //++(自增) --(自减) 一元允运算 int a =3; //a = a+1-----4 int b=a++; //执行完这行代码后,先给b赋值,再自增 System.out.pr ...
- AtCoder Beginner Contest 265(D-E)
D - Iroha and Haiku (New ABC Edition) 题意: 找一个最少含有三个点的区间,将区间分成三块,三块的和分别为p,q,r,问是否存在这样的区间 题解:先预处理一遍前缀和 ...
- 线程池:ThreadPoolExecutor源码解读
目录 1 带着问题去阅读 1.1 线程池的线程复用原理 1.2 线程池如何管理线程 1.3 线程池配置的重要参数 1.4 shutdown()和shutdownNow()区别 1.5 线程池中的两个锁 ...
- 如何修改SAO用户密码
KingbaseES SAO 用户是专门用于审计管理的用户,用户配置审计策略需要使用该用户.在initdb 完成后,SAO 用户的默认密码保存在参数 sysaudit.audit_table_pas ...
- 电商平台物流模块自建OR对接第三方物流平台
前沿 近几年来,电商行业竞争变得愈加激烈,公域流量获客成本越来越高,电商平台规则也越来越严格,数据无法出塔,商家无法自主运营用户群等等原因,很多大品牌纷纷开始搭建自有商城,运营私域流量,以此来降低 ...
- Python数据科学手册-机器学习: 主成分分析
PCA principal component analysis 主成分分析是一个快速灵活的数据降维无监督方法, 可视化一个包含200个数据点的二维数据集 x 和 y有线性关系,无监督学习希望探索x值 ...
- 四、frp内网穿透服务端frps.ini各配置参数详解
[必须]标识头[common]是不可或缺的部分 [必须]服务器IPbind_addr = 0.0.0.00.0.0.0为服务器全局所有IP可用,假如你的服务器有多个IP则可以这样做,或者填写为指定其中 ...
- 5.Ceph 基础篇 - 认证
文章转载自:https://mp.weixin.qq.com/s?__biz=MzI1MDgwNzQ1MQ==&mid=2247485272&idx=1&sn=4b27c357 ...
- Kibana可视化数据(Visualize)
在侧边导航栏点击 Visualize 开始视化您的数据. Visualize 工具能让您通过多种方式浏览您的数据.例如:我们使用饼图这个重要的可视化控件来查看银行账户样本数据中的账户余额.点击屏幕中间 ...