We may encounter json editing problems, especially if the JSON is still large, and the textarea of the input may not meet our needs. Therefore, it would be convenient to have a convenient JSON rich text editor, as shown in the following component example:

  1. First you need to install dependencies codemirror, script-Loader, and JsonLint
npm install codemirror
npm install --save script-loader
npm install --save jsonlint
Copy the code
  1. Encapsulate a VUE component
<template> <div class="json-editor"> <textarea ref="textarea" /> </div> </template> <style scoped> .json-editor { height: calc(100vh - 600px); min-height: 400px; line-height: 20px; } .json-editor >>> .CodeMirror { height: 100%; min-height: 300px; } .json-editor >>> .CodeMirror-scroll { min-height: 300px; } .json-editor >>> .cm-s-rubyblue span.cm-string { color: #F08047; } </style> <script> import CodeMirror from 'codemirror' import 'codemirror/addon/lint/lint.css' import 'codemirror/lib/codemirror.css' import 'codemirror/theme/idea.css' import 'codemirror/mode/javascript/javascript' import  'codemirror/addon/lint/lint' import 'codemirror/addon/lint/json-lint' // eslint-disable-next-line require('script-loader! jsonlint') export default { name: 'JsonEditor', /* eslint-disable vue/require-prop-types */ props: ['value'], data () { return { jsonEditor: false } }, watch: { value (value) { const editorValue = this.jsonEditor.getValue() if (value ! == editorValue) { this.jsonEditor.setValue(JSON.stringify(this.value, null, 2)) } } }, mounted () { this.jsonEditor = CodeMirror.fromTextArea(this.$refs.textarea, { lineNumbers: true, mode: 'application/json', gutters: ['CodeMirror-lint-markers'], theme: 'idea', lint: true }) this.jsonEditor.setValue(JSON.stringify(this.value, null, 2)) this.jsonEditor.on('change', cm => { this.$emit('changed', cm.getValue()) this.$emit('input', cm.getValue()) }) }, methods: { getValue () { return this.jsonEditor.getValue() } } } </script>Copy the code
  1. Encapsulate calling
<json-editor ref="jsonEditor" v-model="resources" />
...
import JsonEditor from './view/json_editor'
...
components: { JsonEditor }
...
data () {
    return {
      resources: {},
    }
  },
Copy the code