干燥机配套车间生产管理系统/云平台前端
baoshiwei
2023-03-10 1fb197352b6a263646e4ccd3ed1c7854ede031dd
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
<template>
  <div class="h-full">
    <CodeMirrorEditor :value="getValue" @change="handleValueChange" :mode="mode" :readonly="readonly" />
  </div>
</template>
 
<script lang="ts">
  const MODE = {
    JSON: 'application/json',
    html: 'htmlmixed',
    js: 'javascript',
  };
</script>
<script lang="ts" setup>
  import { computed } from 'vue';
  import CodeMirrorEditor from './codemirror/CodeMirror.vue';
  import { isString } from '/@/utils/is';
 
  const props = defineProps({
    value: { type: [Object, String] as PropType<Record<string, any> | string> },
    mode: { type: String, default: MODE.JSON },
    readonly: { type: Boolean },
    autoFormat: { type: Boolean, default: true },
  });
 
  const emit = defineEmits(['change', 'update:value', 'format-error']);
 
  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 (e) {
        emit('format-error', value);
        return value as string;
      }
    }
    return JSON.stringify(result, null, 2);
  });
 
  function handleValueChange(v) {
    emit('update:value', v);
    emit('change', v);
  }
</script>