DurationConfig.vue 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <template>
  2. <div>
  3. <div style="margin-bottom: 10px;">当前选择:<el-input v-model="isoString" readonly style="width: 300px;" /></div>
  4. <div v-for="unit in units" :key="unit.key" style="margin-bottom: 8px;">
  5. <span>{{ unit.label }}:</span>
  6. <el-button-group>
  7. <el-button v-for="val in unit.presets" :key="val" size="mini" @click="setUnit(unit.key, val)">{{ val }}</el-button>
  8. <el-input v-model.number="custom[unit.key]" size="mini" style="width: 60px; margin-left: 8px;" placeholder="自定义" @change="setUnit(unit.key, custom[unit.key])" />
  9. </el-button-group>
  10. </div>
  11. </div>
  12. </template>
  13. <script setup>
  14. import { ref, watch, computed } from 'vue'
  15. const props = defineProps({ value: String })
  16. const emit = defineEmits(['change'])
  17. const units = [
  18. { key: 'Y', label: '年', presets: [1, 2, 3, 4] },
  19. { key: 'M', label: '月', presets: [1, 2, 3, 4] },
  20. { key: 'D', label: '天', presets: [1, 2, 3, 4] },
  21. { key: 'H', label: '时', presets: [4, 8, 12, 24] },
  22. { key: 'm', label: '分', presets: [5, 10, 30, 50] },
  23. { key: 'S', label: '秒', presets: [5, 10, 30, 50] }
  24. ]
  25. const custom = ref({ Y: '', M: '', D: '', H: '', m: '', S: '' })
  26. const isoString = ref('')
  27. function setUnit(key, val) {
  28. if (!val || isNaN(val)) {
  29. custom.value[key] = ''
  30. return
  31. }
  32. custom.value[key] = val
  33. updateIsoString()
  34. }
  35. function updateIsoString() {
  36. let str = 'P'
  37. if (custom.value.Y) str += custom.value.Y + 'Y'
  38. if (custom.value.M) str += custom.value.M + 'M'
  39. if (custom.value.D) str += custom.value.D + 'D'
  40. if (custom.value.H || custom.value.m || custom.value.S) str += 'T'
  41. if (custom.value.H) str += custom.value.H + 'H'
  42. if (custom.value.m) str += custom.value.m + 'M'
  43. if (custom.value.S) str += custom.value.S + 'S'
  44. isoString.value = str === 'P' ? '' : str
  45. emit('change', isoString.value)
  46. }
  47. watch(() => props.value, (val) => {
  48. if (!val) return
  49. // 解析ISO 8601字符串到custom
  50. const match = val.match(/^P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/)
  51. if (match) {
  52. custom.value.Y = match[1] || ''
  53. custom.value.M = match[2] || ''
  54. custom.value.D = match[3] || ''
  55. custom.value.H = match[4] || ''
  56. custom.value.m = match[5] || ''
  57. custom.value.S = match[6] || ''
  58. updateIsoString()
  59. }
  60. }, { immediate: true })
  61. </script>