CodeEditor.vue 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. import { defineComponent, computed } from 'vue';
  13. import CodeMirrorEditor from './codemirror/CodeMirror.vue';
  14. import { isString } from '/@/utils/is';
  15. const MODE = {
  16. JSON: 'application/json',
  17. html: 'htmlmixed',
  18. js: 'javascript',
  19. };
  20. const props = {
  21. value: { type: [Object, String] as PropType<Record<string, any> | string> },
  22. mode: { type: String, default: MODE.JSON },
  23. readonly: { type: Boolean },
  24. };
  25. export default defineComponent({
  26. name: 'CodeEditor',
  27. components: { CodeMirrorEditor },
  28. props,
  29. emits: ['change'],
  30. setup(props, { emit }) {
  31. const getValue = computed(() => {
  32. const { value, mode } = props;
  33. if (mode !== MODE.JSON) {
  34. return value as string;
  35. }
  36. return isString(value)
  37. ? JSON.stringify(JSON.parse(value), null, 2)
  38. : JSON.stringify(value, null, 2);
  39. });
  40. function handleValueChange(v) {
  41. emit('change', v);
  42. }
  43. return { handleValueChange, getValue };
  44. },
  45. });
  46. </script>