目录
将textarea容器转换为编辑器,CodeMirror.fromTextArea(refs,{配置项})
背景
项目中需要前端做一个sql编辑器,能够实现sql语句的格式化、自动匹配大小写、自动提示关键词、表名和字段名,关键词高亮显示等功能。经过一番调研,我最终选择使用sql-formatter和codemirror来实现。
sql-formatter:用于sql格式化的工具。
codemirror:代码编辑插件,拥有丰富的api和可扩展功能以及多个主题样式;支持大量语言的语法高亮,包括C、C++、C#、Java、Perl、PHP、JavaScript、Python、Lua、Go、Groovy、Ruby等,以及diff、LaTeX、SQL、wiki、Markdown等文件格式。此外,CodeMirror还支持代码自动完成、搜索/替换、HTML预览、行号、选择/搜索结果高亮、可视化tab、Emacs/VIM键绑定、代码自动格式等。
安装
npm install --save sql-formatter
npm install --save vue-codemirror
使用
sql-formatter的使用
-
引入sql-formatter
import sqlFormatter from 'sql-formatter';
-
使用
//获取格式化SQL var formatSql = sqlFormatter.format('SELECT * FROM A', { language: 'sql', indent: ' ' });
其中language代表格式化SQL的类型(sql为标准格式)、indent代表格式化缩进的字符。
codemirror的使用
-
引入codeMirror必须文件和自动提示、高亮显示等插件
// 引入核心样式
import 'codemirror/theme/ambiance.css';
import 'codemirror/lib/codemirror.css';
import 'codemirror/addon/hint/show-hint.css';
// 引入全局实例
const CodeMirror = require('codemirror/lib/codemirror');
//
require('codemirror/addon/edit/matchbrackets');
require('codemirror/addon/selection/active-line');
// sql语言包
require('codemirror/mode/sql/sql');
// 代码自动提示插件
require('codemirror/addon/hint/show-hint');
require('codemirror/addon/hint/sql-hint');
-
在html中新建textarea标签,用于生成代码框
<template>
<div>
<textarea ref="sqlEditor" v-model="value" class="codesql"></textarea>
</div>
</template>
-
将textarea容器转换为编辑器,CodeMirror.fromTextArea(refs,{配置项})
this.editor = CodeMirror.fromTextArea(this.$refs.sqlEditor, {
value: this.value,
mode: { name: 'text/x-mysql' },
indentWithTabs: true,
smartIndent: true,
lineNumbers: true,
matchBrackets: true,
cursorHeight: 1,
lineWrapping: true,
readOnly: this.readOnly,
// theme: theme,
autofocus: true,
extraKeys: { Ctrl: 'autocomplete' },
hintOptions: {
completeSingle: false,
tables: this.tables
}
});
下面介绍本项目中用到的配置项
(更多配置项参考:https://blog.csdn.net/JLU_Lei/article/details/80259697)
value:初始内容
mode:设置编译器对应的语言
indentWithTabs:是否tabs缩进
smartIndent:自动缩进是否开启
lineNumbers:是否显示行号
matchBrackets:匹配结束符号
cursorHeight:光标高度
readOnly:是否只读
theme:设置主题
autofocus:自动聚焦
extraKeys: { Ctrl: 'autocomplete' }, /自定义快捷键
hintOptions: { completeSingle: false, tables:[] } 自定义提示选项,是否自动补全
-
编辑器事件监听
触发器使用方法:editor.on('chang', ()=>{})
取消触发器方法:ediotr.off('change')
可以监听的事件如下:
- “changes”:每次编辑器内容更改时触发
- “beforeChange”:事件在更改生效前触发
- “cursorActivity”:当光标或选中(内容)发生变化,或者编辑器的内容发生了更改的时候触发。
- “keyHandled”:快捷键映射(key map)中的快捷键被处理(handle)后触发
- “inputRead”:当用户输入或粘贴到编辑器时触发。
- “electrictInput”:收到指定的electrict输入时触发
- “beforeSelectionChange”:此事件在选中内容变化前触发
- “viewportChange”:编辑器的视口( view port )改变(滚动,编辑或其它动作)时触发
- “gutterClick”:编辑器的gutter(行号区域)点击时触发
- “focus”:编辑器收到焦点时触发
- “blur”:编辑器失去焦点时触发
- “scroll”:编辑器滚动条滚动时触发
- “keydown”, “keypress”, “keyup”,“mousedown”, “dblclick”硬件事件触发器
本项目中使用的事件监听如下:
// 监听inputRead事件,实现代码自动提示功能
this.editor.on('inputRead', () => {
this.editor.showHint();
});
-
API
本项目中用到了setValue()和getValue()方法
- this.CodeMirrorEditor.setValue(“Hello Kitty”):设置编辑器内容
- this.CodeMirrorEditor.getValue():获取编辑器内容
- this.CodeMirrorEditor.getLine(n):获取第n行的内容
- this.CodeMirrorEditor.lineCount():获取当前行数
- this.CodeMirrorEditor.lastLine():获取最后一行的行号
- this.CodeMirrorEditor.isClean():boolean类型判断编译器是否是clean的
- this.CodeMirrorEditor.getSelection():获取选中内容
- this.CodeMirrorEditor.getSelections():返回array类型选中内容
- this.CodeMirrorEditor.replaceSelection(“替换后的内容”):替换选中的内容
- this.CodeMirrorEditor.getCursor():获取光标位置,返回{line,char}
- this.CodeMirrorEditor.setOption("",""):设置编译器属性
- this.CodeMirrorEditor.getOption(""):获取编译器属性
- this.CodeMirrorEditor.addKeyMap("",""):添加key-map键值,该键值具有比原来键值更高的优先级
- this.CodeMirrorEditor.removeKeyMap(""):移除key-map
- this.CodeMirrorEditor.addOverlay(""):Enable a highlighting overlay…没试出效果
- this.CodeMirrorEditor.removeOverlay(""):移除Overlay
- this.CodeMirrorEditor.setSize(width,height):设置编译器大小
- this.CodeMirrorEditor.scrollTo(x,y):设置scroll到position位置
- this.CodeMirrorEditor.refresh():刷新编辑器
- this.CodeMirrorEditor.execCommand(“命令”):执行命令
封装一个sql编辑器
以上面介绍的codemirror为基础,封装一个sql编辑器,还需要能够实现编辑器(子组件)和其父组件之间的数据通信。
props: {
// 接收父组件传值
value: {
type: String,
default: ''
},
sqlStyle: {
type: String,
default: 'default'
},
readOnly: {
type: [Boolean, String]
},
// 父组件将表结构传给编辑器,实现自动提示表名和字段名的功能
tables: {
type: Object,
default: () => {}
}
},
data() {
return {
editor: null
};
},
computed: {
// 将编辑器中的值赋给newVal变量
newVal() {
if (this.editor) {
return this.editor.getValue();
}
}
},
watch: {
// 监听newVal值的变化,通过getValue方法获取到值并传递给父组件
newVal(newV, oldV) {
if (this.editor) {
this.$emit('changeTextarea', this.editor.getValue());
}
},
// 将value赋值给编辑器配置项中的value
value(newV, oldV) {
if (this.editor) {
if (newV === '') {
this.editor.setValue('');
}
}
}
}
在父组件中使用
import SqlEditor from './SqlEditor'; // 引入sql编辑器 import sqlFormatter from 'sql-formatter'; // 引入sql格式化工具
HTML写法:
<el-dialog
title="可视化SQL插件"
:visible.sync="sqlVisible"
:area="[560, 450]"
@close="cancelSql(sqlInfo)"
>
<SqlEditor
v-if="sqlVisible"
ref="sqleditor"
:value="sqlInfo"
:tables="sqlTable"
@changeTextarea="changeTextarea($event)"
/>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="formaterSql(sqlInfo)">
格式化sql
</el-button>
<el-button type="primary" @click="confirmSql(sqlInfo)">
确 定
</el-button>
<el-button @click="cancelSql()">取 消</el-button>
</div>
</el-dialog>
JS写法:
// 拿到sql编辑器内容
changeTextarea(val) {
this.sqlInfo = val;
},
// 格式化sql
formaterSql(val) {
const dom = this.$refs.sqleditor;
dom.editor.setValue(sqlFormatter.format(dom.editor.getValue()));
},
// 将编辑器内容赋值给表单输入框
confirmSql(val) {
this.$set(this.form, this.sqlKey, val);
}
//打开sql编辑器时再将输入框内容回显到编辑器中
showSqlDialog(key, index, innerKey) {
if (index === undefined) {
this.sqlKey = key;
this.$nextTick(() => {
const dom = this.$refs.sqleditor;
dom.editor.setValue(this.form[key]);
});
}
},