使用帶逗號分割的字符串填充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>
作者:Tyler Ning
出處:http://www.rzrgm.cn/tylerdonet/
本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,如有問題,請微信聯系冬天里的一把火
浙公網安備 33010602011771號