官方 https://github.com/surmon-china/vue-codemirror/tree/v4.0.1
npm install --save sql-formatter@2.3.3
npm install --save vue-codemirror@4.0.1
npm install --save vue-highlightjs
注意
需要注意vue-codemirror不能选取新版本,新版本需要vue3支持
SqlEditor.vue
<template>
<div>
<textarea ref="mycode" :value="sqlValue"> </textarea>
</div>
</template>
<script>
import "codemirror/theme/ambiance.css";
import "codemirror/lib/codemirror.css";
import "codemirror/addon/hint/show-hint.css";
import CodeMirror from "codemirror";
import "codemirror/addon/edit/matchbrackets";
import "codemirror/addon/selection/active-line";
import "codemirror/mode/sql/sql";
import "codemirror/addon/hint/show-hint";
import "codemirror/addon/hint/sql-hint";
export default {
data() {
return {
editor: null,
};
},
props: {
sqlValue: {
type: String,
default: "",
},
sqlStyle: {
type: String,
default: "default",
},
readOnly: {
type: [Boolean, String],
},
},
watch: {
newVal() {
if (this.editor) {
this.$emit("changeTextarea", this.editor.getValue());
}
},
},
computed: {
newVal() {
if (this.editor) {
return this.editor.getValue();
} else {
return "";
}
},
},
mounted() {
let mime = "text/x-mariadb";
this.editor = CodeMirror.fromTextArea(this.$refs.mycode, {
value: this.sqlValue,
mode: mime, //选择对应代码编辑器的语言,我这边选的是数据库,根据个人情况自行设置即可
indentWithTabs: true,
smartIndent: true,
lineNumbers: true,
matchBrackets: true,
cursorHeight: 1,
lineWrapping: true,
readOnly: this.readOnly,
theme: this.sqlStyle, //ambiance
// autofocus: true,
extraKeys: { Ctrl: "autocomplete" }, //自定义快捷键
hintOptions: {
//自定义提示选项
// 当匹配只有一项的时候是否自动补全
completeSingle: false,
},
});
//代码自动提示功能,记住使用cursorActivity事件不要使用change事件,这是一个坑,那样页面直接会卡死
this.editor.on("inputRead", () => {
this.editor.showHint();
});
},
methods: {
setVal() {
if (this.editor) {
if (this.sqlValue === "") {
this.editor.setValue("");
} else {
this.editor.setValue(this.sqlValue);
}
}
},
},
};
</script>
<style>
.CodeMirror {
color: black;
direction: ltr;
line-height: 22px;
text-align: left;
border: 1px solid #f3f3f3;
}
.CodeMirror-hints {
z-index: 9999 !important;
}
</style>
<template>
<div class="home">
<SqlEditor
ref="sqleditor"
:sql-value="mForm.mSqlStr"
@changeTextarea="changeTextarea($event)"
/>
<input
type="button"
class="sql-btn"
@click="formaterSql(mForm.mSqlStr)"
value="格式化"
/>
</div>
</template>
<script>
import sqlFormatter from "sql-formatter";
import SqlEditor from "@/components/SqlEditor";
export default {
components: {
SqlEditor,
},
data() {
return {
mForm: {
mSqlStr: "",
},
};
},
methods: {
changeTextarea(obj) {
this.$set(this.mForm, "mSqlStr", obj);
},
formaterSql() {
let sqleditor = this.$refs.sqleditor;
sqleditor.editor.setValue(
sqlFormatter.format(sqleditor.editor.getValue())
);
},
},
};
</script>
<style>
.home {
text-align: left;
}
.sql-btn {
margin-top: 10px;
cursor: pointer;
}
</style>