wujingjing
2024-12-30 849603716bd60432e2c1dccb71d8ecf1e03ba866
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<template>
    <div class="flex gap-2 flex-wrap">
        <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"
            v-model="inputValue"
            class="w-32"
            size="small"
            @keyup.enter="handleInputConfirm"
            @blur="handleInputConfirm"
        />
        <el-button v-else class="button-new-tag" size="small" @click="showInput"> + {{ newLabel }} </el-button>
    </div>
</template>
 
<script lang="ts" setup>
import { nextTick, ref } from 'vue';
import { ElInput } from 'element-plus';
import type { InputInstance } from 'element-plus';
 
const props = defineProps({
    newLabel: {
        type: String,
        default: '添加',
    },
});
 
const inputValue = ref('');
const dynamicTags = defineModel({
    type: Array<string>,
});
 
const inputVisible = ref(false);
const InputRef = ref<InputInstance>();
 
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) {
        if (!dynamicTags.value) {
            dynamicTags.value = [];
        }
        dynamicTags.value.push(inputValue.value);
    }
    inputVisible.value = false;
    inputValue.value = '';
};
</script>