当前位置:   article > 正文

基于JS和vue的sql编辑器功能的实现_前端sql编辑器

前端sql编辑器

 

目录

背景

安装

使用

sql-formatter的使用

引入sql-formatter

使用

codemirror的使用

引入codeMirror必须文件和自动提示、高亮显示等插件

在html中新建textarea标签,用于生成代码框

将textarea容器转换为编辑器,CodeMirror.fromTextArea(refs,{配置项})

编辑器事件监听

API

封装一个sql编辑器

在父组件中使用


背景

项目中需要前端做一个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';

     

  • 使用

    1. //获取格式化SQL
    2. var formatSql = sqlFormatter.format('SELECT * FROM A', { language: 'sql', indent: ' ' });

    其中language代表格式化SQL的类型(sql为标准格式)、indent代表格式化缩进的字符。

codemirror的使用

  • 引入codeMirror必须文件和自动提示、高亮显示等插件

  1. // 引入核心样式
  2. import 'codemirror/theme/ambiance.css';
  3. import 'codemirror/lib/codemirror.css';
  4. import 'codemirror/addon/hint/show-hint.css';
  5. // 引入全局实例
  6. const CodeMirror = require('codemirror/lib/codemirror');
  7. //
  8. require('codemirror/addon/edit/matchbrackets');
  9. require('codemirror/addon/selection/active-line');
  10. // sql语言包
  11. require('codemirror/mode/sql/sql');
  12. // 代码自动提示插件
  13. require('codemirror/addon/hint/show-hint');
  14. require('codemirror/addon/hint/sql-hint');
  • 在html中新建textarea标签,用于生成代码框

  1. <template>
  2. <div>
  3. <textarea ref="sqlEditor" v-model="value" class="codesql"></textarea>
  4. </div>
  5. </template>
  • 将textarea容器转换为编辑器,CodeMirror.fromTextArea(refs,{配置项})

  1. this.editor = CodeMirror.fromTextArea(this.$refs.sqlEditor, {
  2. value: this.value,
  3. mode: { name: 'text/x-mysql' },
  4. indentWithTabs: true,
  5. smartIndent: true,
  6. lineNumbers: true,
  7. matchBrackets: true,
  8. cursorHeight: 1,
  9. lineWrapping: true,
  10. readOnly: this.readOnly,
  11. // theme: theme,
  12. autofocus: true,
  13. extraKeys: { Ctrl: 'autocomplete' },
  14. hintOptions: {
  15. completeSingle: false,
  16. tables: this.tables
  17. }
  18. });

下面介绍本项目中用到的配置项

(更多配置项参考: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”硬件事件触发器

本项目中使用的事件监听如下:

  1. // 监听inputRead事件,实现代码自动提示功能
  2. this.editor.on('inputRead', () => {
  3. this.editor.showHint();
  4. });
  • 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编辑器,还需要能够实现编辑器(子组件)和其父组件之间的数据通信。

  1. props: {
  2. // 接收父组件传值
  3. value: {
  4. type: String,
  5. default: ''
  6. },
  7. sqlStyle: {
  8. type: String,
  9. default: 'default'
  10. },
  11. readOnly: {
  12. type: [Boolean, String]
  13. },
  14. // 父组件将表结构传给编辑器,实现自动提示表名和字段名的功能
  15. tables: {
  16. type: Object,
  17. default: () => {}
  18. }
  19. },
  20. data() {
  21. return {
  22. editor: null
  23. };
  24. },
  25. computed: {
  26. // 将编辑器中的值赋给newVal变量
  27. newVal() {
  28. if (this.editor) {
  29. return this.editor.getValue();
  30. }
  31. }
  32. },
  33. watch: {
  34. // 监听newVal值的变化,通过getValue方法获取到值并传递给父组件
  35. newVal(newV, oldV) {
  36. if (this.editor) {
  37. this.$emit('changeTextarea', this.editor.getValue());
  38. }
  39. },
  40. // 将value赋值给编辑器配置项中的value
  41. value(newV, oldV) {
  42. if (this.editor) {
  43. if (newV === '') {
  44. this.editor.setValue('');
  45. }
  46. }
  47. }
  48. }

在父组件中使用

import SqlEditor from './SqlEditor';    // 引入sql编辑器

import sqlFormatter from 'sql-formatter';   // 引入sql格式化工具

HTML写法:

  1. <el-dialog
  2. title="可视化SQL插件"
  3. :visible.sync="sqlVisible"
  4. :area="[560, 450]"
  5. @close="cancelSql(sqlInfo)"
  6. >
  7. <SqlEditor
  8. v-if="sqlVisible"
  9. ref="sqleditor"
  10. :value="sqlInfo"
  11. :tables="sqlTable"
  12. @changeTextarea="changeTextarea($event)"
  13. />
  14. <div slot="footer" class="dialog-footer">
  15. <el-button type="primary" @click="formaterSql(sqlInfo)">
  16. 格式化sql
  17. </el-button>
  18. <el-button type="primary" @click="confirmSql(sqlInfo)">
  19. 确 定
  20. </el-button>
  21. <el-button @click="cancelSql()">取 消</el-button>
  22. </div>
  23. </el-dialog>

JS写法: 

  1. // 拿到sql编辑器内容
  2. changeTextarea(val) {
  3. this.sqlInfo = val;
  4. },
  5. // 格式化sql
  6. formaterSql(val) {
  7. const dom = this.$refs.sqleditor;
  8. dom.editor.setValue(sqlFormatter.format(dom.editor.getValue()));
  9. },
  10. // 将编辑器内容赋值给表单输入框
  11. confirmSql(val) {
  12. this.$set(this.form, this.sqlKey, val);
  13. }
  14. //打开sql编辑器时再将输入框内容回显到编辑器中
  15. showSqlDialog(key, index, innerKey) {
  16. if (index === undefined) {
  17. this.sqlKey = key;
  18. this.$nextTick(() => {
  19. const dom = this.$refs.sqleditor;
  20. dom.editor.setValue(this.form[key]);
  21. });
  22. }
  23. },

 

 

 

 

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/710231
推荐阅读
相关标签
  

闽ICP备14008679号