其他分享
首页 > 其他分享> > VUE CodeMirrorr+json-lint实现可编辑的Json-Editor组件 动态调用多次时出现格式错误问题

VUE CodeMirrorr+json-lint实现可编辑的Json-Editor组件 动态调用多次时出现格式错误问题

作者:互联网

 在不同的Tab下都调用了json编辑组件,导致第二个页面json格式变成:

 解决方法:

在配置项中添加:autoRefresh: true 需要刷新

代码:

<template>
  <div class="json-editor">
    <textarea ref="textarea" />
  </div>
</template>

<script>
import CodeMirror from 'codemirror'
import 'codemirror/addon/lint/lint.css'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/monokai.css'
require('script-loader!jsonlint')
import 'codemirror/mode/javascript/javascript'
import 'codemirror/addon/lint/lint'
import 'codemirror/addon/lint/json-lint'
import 'codemirror/addon/display/autorefresh'

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() {
    // CodeMirror.fromTextArea()中第一个参数是DOM元素,而且必须是textarea元素;第二个参数是可选配置项
    this.jsonEditor = CodeMirror.fromTextArea(this.$refs.textarea, {
      lineNumbers: true,
      mode: 'application/json',
      gutters: ['CodeMirror-lint-markers'],
      theme: 'monokai',
      lint: true,
      readOnly: true,
      autoRefresh: 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>

<style scoped>
.json-editor{
  height: 100%;
  position: relative;
}
.json-editor >>> .CodeMirror {
  height: auto;
  min-height: 300px;
}
.json-editor >>> .CodeMirror-scroll{
  min-height: 300px;
}
.json-editor >>> .cm-s-rubyblue span.cm-string {
  color: #F08047;
}
.addbtn{
  margin-bottom: 15px;
  margin-left: 30px;
}
</style>

官方链接CodeMirror

标签:VUE,CodeMirror,lint,json,Json,import,jsonEditor,codemirror
来源: https://blog.csdn.net/ka_xingl/article/details/121115579