jsonEditor.vue 2.38 KB
<template>
  <div class="flex flex-col justify-between">
    <div ref="jsoneditorRef" style="height: 100%"></div>
    <div class="ml-2 -mt-1.5">
      <Button v-if="showBtn" @click="onHandleCopy" class="mt-8 -ml-2">
        <template #icon>
          <CopyOutlined />
        </template>
        copy
      </Button>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted, nextTick, unref } from 'vue';
  import jsoneditor from 'jsoneditor';
  import 'jsoneditor/dist/jsoneditor.min.css';
  import { Button } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { CopyOutlined } from '@ant-design/icons-vue';

  const props = defineProps({
    showBtn: {
      type: Boolean,
      default: false,
    },
  });

  const { createMessage } = useMessage();

  // json 以及初始化JSON
  const jsoneditorRef = ref();

  const jsonValue = ref({});

  const jsonInstance = ref();

  onMounted(() => {
    nextTick(() => {
      let options = {
        mode: 'code',
        mainMenuBar: false,
        statusBar: false,
        onFocus: () => {},
        onBlur: () => {},
        onChangeText: (e) => {
          if (props.showBtn) {
            if (e.length) return setJsonValue('测试结果为');
          }
        },
      } as object;
      let editor = new jsoneditor(jsoneditorRef.value, options);
      editor.set(jsonValue.value);
      jsonInstance.value = editor;
    });
  });

  const getJsonValue = () => unref(jsonInstance).get();

  const setJsonMode = (mode) => {
    nextTick(() => {
      unref(jsonInstance).setMode(mode);
    });
  };

  const setJsonValue = (Json) => {
    nextTick(() => {
      unref(jsonInstance).set(Json);
    });
  };

  function copyToClip(content, message) {
    var aux = document.createElement('input');
    aux.setAttribute('value', content);
    document.body.appendChild(aux);
    aux.select();
    document.execCommand('copy');
    document.body.removeChild(aux);
    if (message == null) {
      createMessage.success('复制成功!');
    } else {
    }
  }

  const onHandleCopy = () => {
    copyToClip(JSON.stringify(getJsonValue()), null);
  };

  defineExpose({
    getJsonValue,
    setJsonValue,
    jsonInstance,
    setJsonMode,
  });
</script>

<style>
  .jsoneditor {
    border: none;
  }
</style>