用户在文本框中输入1,2,3,4,5 ,然后直接转变成tag,如果输入错误,可以直接点击叉号关闭当前,前端代码实现如下:
<template><el-input-tagref="inputRef"tag-type="primary"v-model="obj.model"clearable@paste.native="handleInput":placeholder="props.prop.placeholder || props.prop.label || ''"></el-input-tag>
</template><script setup>import { nextTick, ref, defineModel, defineEmits, reactive } from 'vue'import { noEmptyArray } from '@/common/utils'const name = 'tl-input-tags'const model = defineModel([])const inputValue = ref('')const inputVisible = ref(false)const inputRef = ref('')const emit = defineEmits(['valueChange'])const obj = reactive({model: [],})const props = defineProps({prop: { type: Object, default: () => ({}) }, //属性对象})// 输入框输入事件const handleInput = (e) => {e.preventDefault()const clipboardData = e.clipboardData || window.clipboardDataconst pastedText = clipboardData.getData('text/plain')const rows = pastedText.trim() // 去除首尾空白.split(/\r\n|\n|\r|,|,/) // 处理不同系统的换行符if (noEmptyArray(rows)) {if (noEmptyArray(obj.model)) {obj.model = [...obj.model, ...rows]} else {obj.model = rows}}emit('valueChange', model.value)}const handleTagAdd = (val) => {const elInput = inputRef.value?.$el.querySelector('.el-input-tag__input')elInput.value = ''}// 显示输入框const showInput = () => {inputVisible.value = truenextTick(() => {inputRef.value?.input?.focus()})}// 删除一个tagconst handleClose = (i) => {model.value.splice(i, 1)nextTick(() => {emit('valueChange', model.value)})}// 确认输入框内容const handleInputConfirm = (e) => {e.preventDefault()if (inputValue.value) {let newTag = inputValue.value.trim().split(',')if (noEmptyArray(model.value)) {model.value.push(...newTag)} else {model.value = newTag}}inputVisible.value = falseinputValue.value = ''nextTick(() => {emit('valueChange', model.value)})}//按下ctrl+v,只能在https下使用const handleInputKeydown = async(e) => {e.preventDefault()const text = await navigator.clipboard.readText()if (text) {let newTag = text.split(',')if (noEmptyArray(model.value)) {model.value.push(...newTag)} else {model.value = newTag}}inputVisible.value = falseinputValue.value = ''nextTick(() => {emit('valueChange', model.value)})}
</script><style lang="scss" scoped>
</style>