gaoluyang
2026-06-24 c0cb161bb52ce0fbdce5c66ec391d107c75e2452
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
<script lang="ts" setup>
import type { CodeEditorProps } from './types';
 
import { computed } from 'vue';
 
import { isString } from '..\..\..\..\utils\src';
 
import CodeMirrorEditor from './code-mirror.vue';
import { MODE } from './types';
 
const props = withDefaults(defineProps<CodeEditorProps>(), {
  value: '',
  mode: MODE.JSON,
  readonly: false,
  autoFormat: true,
  bordered: false,
});
 
const emit = defineEmits(['change', 'update:value', 'formatError']);
 
const getValue = computed(() => {
  const { value, mode, autoFormat } = props;
  if (!autoFormat || mode !== MODE.JSON) return value as string;
 
  let result = value;
  if (isString(value)) {
    try {
      result = JSON.parse(value);
    } catch {
      emit('formatError', value);
      return value as string;
    }
  }
  return JSON.stringify(result, null, 2);
});
 
function handleValueChange(v: string) {
  emit('update:value', v);
  emit('change', v);
}
</script>
 
<template>
  <div class="h-full">
    <CodeMirrorEditor
      :value="getValue"
      :mode="mode"
      :readonly="readonly"
      :bordered="bordered"
      :auto-format="autoFormat"
      @change="handleValueChange"
    />
  </div>
</template>