实现目标
实现思路
在此基础上进行修改,模拟textarea文本框,按钮去掉,直接对input框进样式修改
实现代码
<template>
<div class="w-400px box-textarea" @click="showInput">
<div class="flex gap-2 flex-wrap flex-row">
<el-tag
v-for="tag in dynamicTags"
:key="tag"
closable
:disable-transitions="false"
@close="handleClose(tag)"
>
{{ tag }}
</el-tag>
<el-input
v-if="inputVisible"
ref="InputRef"
placeholder="按回车键Enter创建标签"
v-model="inputValue"
:style="{ width: `${inputValue.length + 125}px` }"
size="small"
@keyup.enter="handleInputConfirm"
@blur="handleInputConfirm"
/>
</div>
</div>
</template>
<script lang="ts" setup>
import { ElInput } from 'element-plus'
import { nextTick, ref } from 'vue'
const inputValue = ref('')
const dynamicTags = ref(['Tag 1', 'Tag 2', 'Tag 3'])
const inputVisible = ref(true)
const InputRef = ref<InstanceType<typeof ElInput>>()
const handleClose = (tag: string) => {
dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
}
const showInput = () => {
inputVisible.value = true
nextTick(() => {
InputRef.value!.input!.focus()
})
}
const handleInputConfirm = () => {
if (inputValue.value) {
dynamicTags.value.push(inputValue.value)
}
inputValue.value = ''
}
</script>
<style scoped lang="scss">
.box-textarea {
width: 400px;
background: #fff;
border: 1px solid #e8eaec;
padding: 10px;
/* 去掉 el-input 的常规边框 */
:deep(.el-input__wrapper) {
box-shadow: none;
padding: 1px 0;
}
}
</style>
实现效果
备注
如果不需要placeholder,el-input的style可设置如下
:style="{ width: `${inputValue.length * 7 + 20}px` }"
默认初始input20px,随着文本长度逐渐递增变宽,length * 系数,系数可根据自己最外层div总宽度进行调整
此功能vue3+ts+element plus+tailwind css直接使用 可根据自己项目进行调整修改