index.vue 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. <template>
  2. <div class="json-editor">
  3. <label>
  4. <textarea ref="textarea" />
  5. </label>
  6. </div>
  7. </template>
  8. <script>
  9. import CodeMirror from "codemirror";
  10. import "codemirror/addon/lint/lint.css";
  11. import "codemirror/lib/codemirror.css";
  12. import "codemirror/theme/rubyblue.css";
  13. import "codemirror/mode/javascript/javascript";
  14. import "codemirror/addon/lint/lint";
  15. import "codemirror/addon/lint/json-lint";
  16. require("script-loader!jsonlint");
  17. export default {
  18. name: "JsonEditor",
  19. props: {
  20. value: {
  21. type: [Array, Object],
  22. default: () => {
  23. return null;
  24. },
  25. },
  26. },
  27. data() {
  28. return {
  29. jsonEditor: false,
  30. };
  31. },
  32. watch: {
  33. value(value) {
  34. const editorValue = this.jsonEditor.getValue();
  35. if (editorValue) {
  36. this.$emit("change", editorValue);
  37. } else {
  38. this.$baseMessage("JSON不能为空,否则无法生成表格", "error");
  39. }
  40. if (value !== editorValue) {
  41. this.jsonEditor.setValue(JSON.stringify(this.value, null, 2));
  42. }
  43. },
  44. },
  45. mounted() {
  46. this.jsonEditor = CodeMirror.fromTextArea(this.$refs.textarea, {
  47. lineNumbers: true,
  48. mode: "application/json",
  49. gutters: ["CodeMirror-lint-markers"],
  50. theme: "rubyblue",
  51. lint: true,
  52. });
  53. this.jsonEditor.setValue(JSON.stringify(this.value, null, 2));
  54. this.jsonEditor.on("change", (cm) => {
  55. if (this.isJsonString(cm.getValue())) {
  56. this.$emit("change", cm.getValue());
  57. }
  58. });
  59. },
  60. methods: {
  61. getValue() {
  62. return this.jsonEditor.getValue();
  63. },
  64. isJsonString(str) {
  65. try {
  66. if (typeof JSON.parse(str) == "object") {
  67. return true;
  68. }
  69. } catch (e) {}
  70. return false;
  71. },
  72. },
  73. };
  74. </script>
  75. <style scoped>
  76. .json-editor {
  77. position: relative;
  78. height: 100%;
  79. }
  80. .json-editor >>> .CodeMirror {
  81. height: auto;
  82. min-height: calc(100vh - 220px);
  83. }
  84. .json-editor >>> .CodeMirror-scroll {
  85. min-height: calc(100vh - 220px);
  86. }
  87. .json-editor >>> .cm-s-rubyblue span.cm-string {
  88. color: #f08047;
  89. }
  90. .json-editor >>> .cm-s-rubyblue .CodeMirror-gutters {
  91. padding-right: 10px;
  92. /* background: transparent; */
  93. border-right: 1px solid #fff;
  94. }
  95. .json-editor >>> .cm-s-rubyblue.CodeMirror {
  96. /* background: #08233e; */
  97. color: white;
  98. }
  99. </style>