Commit e7c96363a1963b7733a9ee498403eb6a062160e6

Authored by 无木
1 parent 93812f73

fix(code-editor): fixed formatting error

修复JSON编辑器在格式化无效JSON文本时会抛出异常的问题
CHANGELOG.zh_CN.md
@@ -4,6 +4,7 @@ @@ -4,6 +4,7 @@
4 4
5 ### 🐛 Bug Fixes 5 ### 🐛 Bug Fixes
6 6
  7 +- **CodeEditor** 修复 JSON 编辑器在格式化无效 JSON 文本时会抛出异常的问题
7 - **其它** 8 - **其它**
8 - 修复部分封装组件在使用插槽时报错的问题 9 - 修复部分封装组件在使用插槽时报错的问题
9 - 修复`useECharts`的`theme`参数不起作用的问题 10 - 修复`useECharts`的`theme`参数不起作用的问题
src/components/CodeEditor/src/CodeEditor.vue
@@ -25,18 +25,26 @@ @@ -25,18 +25,26 @@
25 value: { type: [Object, String] as PropType<Record<string, any> | string> }, 25 value: { type: [Object, String] as PropType<Record<string, any> | string> },
26 mode: { type: String, default: MODE.JSON }, 26 mode: { type: String, default: MODE.JSON },
27 readonly: { type: Boolean }, 27 readonly: { type: Boolean },
  28 + autoFormat: { type: Boolean, default: true },
28 }); 29 });
29 30
30 - const emit = defineEmits(['change', 'update:value']); 31 + const emit = defineEmits(['change', 'update:value', 'format-error']);
31 32
32 const getValue = computed(() => { 33 const getValue = computed(() => {
33 - const { value, mode } = props;  
34 - if (mode !== MODE.JSON) { 34 + const { value, mode, autoFormat } = props;
  35 + if (!autoFormat || mode !== MODE.JSON) {
35 return value as string; 36 return value as string;
36 } 37 }
37 - return isString(value)  
38 - ? JSON.stringify(JSON.parse(value), null, 2)  
39 - : JSON.stringify(value, null, 2); 38 + let result = value;
  39 + if (isString(value)) {
  40 + try {
  41 + result = JSON.parse(value);
  42 + } catch (e) {
  43 + emit('format-error', value);
  44 + return value as string;
  45 + }
  46 + }
  47 + return JSON.stringify(result, null, 2);
40 }); 48 });
41 49
42 function handleValueChange(v) { 50 function handleValueChange(v) {