使用带逗号分割的字符串填充el-input-tag

用户在文本框中输入1,2,3,4,5 ,然后直接转变成tag,如果输入错误,可以直接点击叉号关闭当前,前端代码实现如下:

<template>
  <el-input-tag
    ref="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.clipboardData
    const 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 = true
    nextTick(() => {
      inputRef.value?.input?.focus()
    })
  }

  // 删除一个tag
  const 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 = false
    inputValue.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 = false
    inputValue.value = ''
    nextTick(() => {
      emit('valueChange', model.value)
    })
  }
</script>

<style lang="scss" scoped>
</style>
posted @ 2025-03-27 10:36  nd  阅读(148)  评论(0)    收藏  举报