1. 下载指定版本的包 (避免引发不必要的错误)
yarn add codemirror@^5.64.0
2. 导入需要的文件
import CodeMirror from 'codemirror'
import 'codemirror/addon/lint/lint.css'
import 'codemirror/addon/fold/foldgutter.css'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/rubyblue.css'
import 'codemirror/mode/javascript/javascript'
import 'codemirror/addon/lint/lint'
import 'codemirror/addon/lint/json-lint'
// 折叠
import 'codemirror/addon/fold/foldgutter.css'
import 'codemirror/addon/fold/foldcode'
import 'codemirror/addon/fold/foldgutter'
import 'codemirror/addon/fold/brace-fold'
import 'codemirror/addon/fold/comment-fold'
3. 注册
<template>
<textarea ref="mycode" class="textarea" v-model="logInfo"></textarea>
</template>
<script>
import * as jsonlint from 'json-lint'
window['jsonlint'] = jsonlint
import CodeMirror from 'codemirror'
import 'codemirror/addon/lint/lint.css'
import 'codemirror/addon/fold/foldgutter.css'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/rubyblue.css'
import 'codemirror/mode/javascript/javascript'
import 'codemirror/addon/lint/lint'
import 'codemirror/addon/lint/json-lint'
// 折叠
import 'codemirror/addon/fold/foldgutter.css'
import 'codemirror/addon/fold/foldcode'
import 'codemirror/addon/fold/foldgutter'
import 'codemirror/addon/fold/brace-fold'
import 'codemirror/addon/fold/comment-fold'
export default {
data() {
return {
logInfo: null,
editorText: null
}
},
components: {},
created() {},
async mounted() {
const result = await this.$api.getLogDataInfo(null, this.$route.query.serialNo)
this.logInfo = JSON.stringify(result)
this.editorText = CodeMirror.fromTextArea(this.$refs.mycode, {
mode: 'application/json',
lineNumbers: true, // 显示行号
tabSize: 2,
lint: true,
styleActiveLine: true,
foldGutter: true, // 启用折叠效果
gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter', 'CodeMirror-lint-markers'], // 配置折叠参数
})
var jsonData = JSON.stringify(result) //result是请求的后台数据
var res = JSON.stringify(JSON.parse(jsonData), null, 4) //格式化后的json字符串形式
this.editorText.setValue(res) //设置数据
// 获取数据
this.editorText.on('change', () => {
console.log(this.editorText.getValue())
})
},
methods: {}
}
</script>
<style lang="scss">
.CodeMirror {
height: 100vh;
overflow: hidden;
}
</style>
4. 效果