wwf
11 小时以前 a1d7e81859f554f3a53680cc35f0f49bf1f77098
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
61
62
63
64
65
66
67
68
69
70
71
72
73
<template>
  <div v-for="(item, index) in items" :key="index" class="flex mb-2 w-full">
    <el-input v-model="item.key" class="mr-2" placeholder="键" />
    <el-input v-model="item.value" placeholder="值" />
    <el-button class="ml-2" text type="danger" @click="removeItem(index)">
      <el-icon>
        <Delete />
      </el-icon>
      删除
    </el-button>
  </div>
  <el-button text type="primary" @click="addItem">
    <el-icon>
      <Plus />
    </el-icon>
    {{ addButtonText }}
  </el-button>
</template>
 
<script lang="ts" setup>
import { Delete, Plus } from '@element-plus/icons-vue'
import { isEmpty } from '@/utils/is'
 
defineOptions({ name: 'KeyValueEditor' })
 
interface KeyValueItem {
  key: string
  value: string
}
 
const props = defineProps<{
  modelValue: Record<string, string>
  addButtonText: string
}>()
const emit = defineEmits(['update:modelValue'])
const items = ref<KeyValueItem[]>([]) // 内部 key-value 项列表
 
/** 添加项目 */
const addItem = () => {
  items.value.push({ key: '', value: '' })
  updateModelValue()
}
 
/** 移除项目 */
const removeItem = (index: number) => {
  items.value.splice(index, 1)
  updateModelValue()
}
 
/** 更新 modelValue */
const updateModelValue = () => {
  const result: Record<string, string> = {}
  items.value.forEach((item) => {
    if (item.key) {
      result[item.key] = item.value
    }
  })
  emit('update:modelValue', result)
}
 
/** 监听项目变化 */
watch(items, updateModelValue, { deep: true })
watch(
  () => props.modelValue,
  (val) => {
    // 列表有值后以列表中的值为准
    if (isEmpty(val) || !isEmpty(items.value)) {
      return
    }
    items.value = Object.entries(props.modelValue).map(([key, value]) => ({ key, value }))
  }
)
</script>