CodeEditor.vue 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <template>
  2. <div class="h-full">
  3. <CodeMirrorEditor
  4. :value="getValue"
  5. @change="handleValueChange"
  6. :mode="mode"
  7. :readonly="readonly"
  8. />
  9. </div>
  10. </template>
  11. <script lang="ts">
  12. const MODE = {
  13. JSON: 'application/json',
  14. html: 'htmlmixed',
  15. js: 'javascript',
  16. };
  17. </script>
  18. <script lang="ts" setup>
  19. import { computed } from 'vue';
  20. import CodeMirrorEditor from './codemirror/CodeMirror.vue';
  21. import { isString } from '/@/utils/is';
  22. const props = defineProps({
  23. value: { type: [Object, String] as PropType<Record<string, any> | string> },
  24. mode: { type: String, default: MODE.JSON },
  25. readonly: { type: Boolean },
  26. });
  27. const emit = defineEmits(['change', 'update:value']);
  28. const getValue = computed(() => {
  29. const { value, mode } = props;
  30. if (mode !== MODE.JSON) {
  31. return value as string;
  32. }
  33. return isString(value)
  34. ? JSON.stringify(JSON.parse(value), null, 2)
  35. : JSON.stringify(value, null, 2);
  36. });
  37. function handleValueChange(v) {
  38. emit('update:value', v);
  39. emit('change', v);
  40. }
  41. </script>