之前项目里要做在线代码编辑器,找了很多最后相比较下来觉得 CodeMirror还不错,所以拿出来给大家分享一下。顺便在此做个记录方便以后查阅。
CodeMirror官网:https://codemirror.net/
第一步:安装插件
npm i codemirror --save
第二步:子组件封装
<template lang="pug">
.json-editor
textarea(ref='textareaCoder')
</template>
<script>
import codeMirror from 'codemirror'
import 'codemirror/lib/codemirror.css'
import 'codemirror/mode/javascript/javascript'
import 'codemirror/theme/rubyblue.css'
import 'codemirror/theme/rubyblue.css'
import 'codemirror/addon/edit/matchbrackets'
import 'codemirror/addon/selection/active-line'
import 'codemirror/addon/edit/closebrackets'
import 'codemirror/addon/display/fullscreen.css'
import 'codemirror/addon/display/fullscreen.js'
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 {
codeEditor: null,
code: '',
}
},
mounted () {
this.initCodeEditor()
},
methods: {
initCodeEditor () {
this.codeEditor = codeMirror.fromTextArea(this.$refs.textareaCoder, {
theme: 'rubyblue',
tabSize: 2,
mode: 'javascript',
smartIndent: true,
styleActiveLine: true,
lint: true,
lineNumbers: true,
foldGutter: true,
gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
matchBrackets: true,
autoCloseBrackets: true,
})
this.codeEditor.on('change', item => {
this.code = item.getValue()
})
this.codeEditor.setOption("extraKeys", {
"F1" (cm) {
cm.setOption("fullScreen", !cm.getOption("fullScreen"));
},
"Esc" (cm) {
if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
}
});
},
setValue (val) {
this.codeEditor.setValue(val)
},
refresh() {
this.codeEditor && this.codeEditor.refresh()
},
}
}
</script>
<style lang="scss" scoped>
.json-editor {
height: 100%;
position: relative;
line-height: initial;
}
.json-editor >>> .CodeMirror {
height: auto;
min-height: 250px;
}
.json-editor >>> .CodeMirror-scroll {
min-height: 250px;
}
.json-editor >>> .cm-s-rubyblue span.cm-string {
color: #f08047;
}
</style>
第三步:父组件引用
<template lang="pug">
div
code-mirror(ref="codeMirror")
</template>
<script>
import CodeMirror from '@/code-mirror/index.vue'
export default {
CodeMirror,
methods: {
refresh() {
this.$refs.codeMirror.refresh()
},
getValue () {
return this.$refs.codeMirror.code
},
setValue (value) {
this.$refs.codeMirror.setValue(value)
},
}
}
</script>
实现的最终效果如下:
|