介绍
在做一个项目时,遇到需要输入若干键值对的需求,在Elementplus组件库里并未找到类似组件,所以自己在elementplus基础上封装了一个
效果
代码
<template>
<template v-for="(item, index) in newLocalValue" :key="index">
<div class="kvInput">
<el-input v-model="newLocalValue[index].key" placeholder="请输入Header Key"/>
<el-input v-model="newLocalValue[index].value" placeholder="请输入Header Value"/>
<el-button type="info" :icon="Delete" circle @click="del(index)"/>
<el-button :icon="Check" circle @click="confirm(index)"/>
</div>
</template>
</template>
<script lang="ts" setup>
import {Delete, Check} from '@element-plus/icons-vue';
import {onMounted, reactive, ref, toRefs} from "vue";
const props = defineProps(['value'])
const emits = defineEmits(['update:value'])
const {value} = toRefs(props)
let localValue = reactive(value?.value)
type newLocalValueOneType = {
key: string;
value: string;
}
const newLocalValue = ref<newLocalValueOneType[]>([])
const initNewLocalValue = () => {
for(let index in Object.keys(localValue)) {
newLocalValue.value.push({
key: Object.keys(localValue)[index],
value: localValue[Object.keys(localValue)[index]]
})
}
}
const addEmpty = () => {
newLocalValue.value.push({
key: '',
value: ''
})
}
onMounted(() => {
initNewLocalValue()
addEmpty()
})
const updateValue = () => {
localValue = {}
for (let item of newLocalValue.value) {
if(item.key) {
localValue[item.key] = item.value
}
}
emits('update:value', localValue)
}
const confirm = (index: number) => {
updateValue()
if(index == newLocalValue.value.length - 1) {
addEmpty()
}
}
const del = (index: number) => {
newLocalValue.value.splice(index, 1)
if(newLocalValue.value.length === 0) {
newLocalValue.value = [{
key: '',
value: ''
}]
}
updateValue()
}
</script>
<style lang="less" scoped>
.kvInput {
display: flex;
justify-content: space-between;
width: 100%;
margin-bottom: 4px;
.el-input {
margin-right: 10px;
}
.el-button {
margin: 0 5px 0 0;
}
}
</style>