使用CodeMirror高亮显示js代码
首先封装在组件中
<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/rubyblue.css';
require('script-loader!jsonlint');
import 'codemirror/mode/javascript/javascript';
import 'codemirror/addon/lint/lint';
import 'codemirror/addon/lint/json-lint';
import "codemirror/theme/3024-day.css";
export default {
name: 'JsonEditor',
/* eslint-disable vue/require-prop-types */
props: {
value: String,
// 只读
readOnly: {
type: Boolean,
defalut: false
},
// 解析代码格式
mode: {
type: String,
defalut: 'application/json'
},
},
data() {
return {
jsonEditor: false
};
},
watch: {
value(value) {
const editorValue = this.jsonEditor.getValue();
if (value !== editorValue) {
this.setModeValue();
}
}
},
mounted() {
this.jsonEditor = CodeMirror.fromTextArea(this.$refs.textarea, {
lineNumbers: true,
mode: this.mode,
gutters: ['CodeMirror-lint-markers'],
theme: '3024-day',
readOnly: this.readOnly,
lint: true
});
if(this.value){
this.setModeValue();
}
this.jsonEditor.on('change', (cm) => {
this.$emit('changed', cm.getValue());
this.$emit('input', cm.getValue());
});
},
methods: {
getValue() {
if (this.jsonEditor.state.lint.marked.length > 0) {
return false;
}
return this.jsonEditor.getValue();
},
// 根据不同mode取值,如果使用JSON.stringify解析字符串,文本框中会自动添加双引号
setModeValue() {
if(this.mode === "javascript") {
this.jsonEditor.setValue(this.value);
} else {
this.jsonEditor.setValue(JSON.stringify(this.value, null, 2));
}
}
}
};
</script>
<style lang="less" scoped>
.json-editor {
height: 100%;
position: relative;
::v-deep {
.CodeMirror {
height: auto;
min-height: 300px;
}
.CodeMirror-scroll {
min-height: 300px;
}
.cm-s-rubyblue span.cm-string {
color: #f08047;
}
}
}
</style>
需要注册之后在子项目中使用
<VenusJsonEditor v-model="editForm.formula" mode="javascript" />

3259

被折叠的 条评论
为什么被折叠?



