vue项目中实现sql编辑器功能自定义高亮词汇可提示关键词-codemirror
先上图:左侧是数据库表,右侧上部是sql编辑器,下部是执行sql的返回接口
HTML:
<el-row>
<el-col :span="4" class="sqlTree">
<el-tree :data="sqlTree" :props="defaultProps" node-key="id" default-expand-all>
<span slot-scope="{ node,data }">
<span v-if="data.icon == 'iconOne'">
<i class="el-icon-folder-opened"></i>{{ node.label }}
</span>
<span v-if="data.icon == 'iconTwo'">
<i class="el-icon-document"></i>{{ node.label }}
</span>
</span>
</el-tree>
</el-col>
<el-col :span="20" class="sqlText">
<div class="sqlBtn">
<el-button class="runBtn" type="primary" icon="el-icon-caret-right" size="mini" @click="handleRestart(true)">运行</el-button>
<el-button class="beatyBtn" type="success" icon="el-icon-magic-stick" size="mini" @click="sqlFormat">美化</el-button>
</div>
<!-- <codemirror ref="myCm" v-model="sqlText" :options="cmOptions" @ready="onCmReady" @focus="onCmFocus" @input="onCmCodeChange"></codemirror> -->
<textarea ref="myCm" class="sqlTextarea" v-model="sqlText"></textarea>
<el-tabs type="border-card" v-if="typeof (sqlInfo.hasResult) != 'undefined'">
<el-tab-pane label="信息" v-if="!sqlInfo.hasResult && !sqlInfo.result">ERROR>> {{sqlInfo.msg}}</el-tab-pane>
<el-tab-pane label="信息" v-if="!sqlInfo.hasResult && sqlInfo.result">INFO>> {{sqlInfo.msg}}</el-tab-pane>
<el-tab-pane label="结果" v-if="sqlInfo.hasResult">
<el-table
:data="sqlInfo.resList"
height="200"
style="width: 100%">
<el-table-column v-for="(item, ind) in sqlInfo.header" :key="ind" :prop="item" :label="item"></el-table-column>
</el-table>
</el-tab-pane>
</el-tabs>
<div class="paginationBox" v-if="sqlInfo.hasResult">
<span>
展示
<!-- <span v-if="this.total"> {{this.pageBean.page == 1 ? 1 : (this.pageBean.page - 1) * 10 + 1}} -</span> -->
{{ sqlInfo.resList.length }} 条数据 ,
总共 {{sqlInfo.total}} 条记录。
</span>
<el-pagination
background
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="pageBean.page"
:page-size="pageBean.pageSize"
:total="sqlInfo.total"
layout="prev, pager, next"
style="float: right"
>
</el-pagination>
</div>
</el-col>
</el-row>
JS:
// codemirror
import { codemirror } from 'vue-codemirror'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/base16-light.css'
import 'codemirror/addon/hint/show-hint.css'
let CodeMirror = require("codemirror/lib/codemirror");
// 高亮
// require("codemirror/mode/sql/sql.js")
require("../../../public/static/sql.js")
require('codemirror/addon/hint/sql-hint.js')
require('codemirror/addon/hint/show-hint.js')
require('codemirror/addon/selection/active-line.js') components: {
codemirror
}, methods: {
//运行
handleRestart(flag) {
this.sqlInfo = {}
this.errorSql = ''
this.payload(async () => {
await this.restartExeTask(flag)
})
},
//运行
async restartExeTask(flag) {
let id = this.$route.query.id ? this.$route.query.id : ''
let param = {
sql: this.editor.getValue(),
taskId: id,
pageSize: 10,
}
// 如果是运行按钮默认第一页
if (flag) {
param.pageIndex = 1
} else {
param.pageIndex = this.pageBean.page
}
let response = await req.post(cig + `/governance/cigResFusionTaskExecute/v1/exeTask`, param);
// sql运行 hasResult:true是表格,其他的是msg
this.sqlInfo = response.data // 如果是运行按钮默认第一页
if (flag) {
this.pageBean.page = 1
}
},
// 美化sql代码
sqlFormat() {
/*获取文本编辑器内容*/
let sqlContent="";
sqlContent=this.editor.getValue();
/*将sql内容进行格式后放入编辑器中*/
this.editor.setValue(sqlFormatter.format(sqlContent));
},
getSelectedRange() {
return { from: this.editor.getCursor(true), to: this.editor.getCursor(false) };
},
checkListChange(value){
if(value == true){
this.tableData[this.rowIndex].detectionRule.push({ name: '空值率探查', type: 'success' });
}else{
this.tableData[this.rowIndex].detectionRule.forEach((item,index)=>{
if(item['name'] == "空值率探查"){
this.tableData[this.rowIndex].detectionRule.remove(item);
}
})
}
},
tagClose(tag,index,rowIndex) {
this.tableData[rowIndex].detectionRule.splice(index, 1);
if(tag['name'] == "空值率探查"){
this.detectionInfo.nullRateDetection = false;
}
},
//下一步
handleNext() {
if (this.stepActive == 0) {
this.$refs['resForm'].validate((valid) => {
if (valid) {
this.stepActive++
} else {
this.$message({ message: '表单数据有误,请确认后重新操作!', type: 'warning' });
return false;
}
});
// 判断是否已经存在codemirror 若存在 则不初始化
if (!this.hasMirror) {
let _this = this
this.$nextTick(() => {
_this.initCdMirror()
})
} }else if(this.stepActive == 1){
this.stepActive++
}
},
// 初始化codemirror
initCdMirror() {
this.editor = CodeMirror.fromTextArea(this.$refs.myCm, {
mode: 'text/xl-sql',//选择对应代码编辑器的语言,我这边选的是数据库,根据个人情况自行设置即可
tabSize: 2,
indentWithTabs: true,
smartIndent: true,
lineNumbers: true,
matchBrackets: true,
theme: 'base16-light',
line: false,
autofocus: true,
hint: CodeMirror.hint.sql,
hintOptions: {
tables: window.tablewords
}
// lineWrapping: true, //是否换行
// foldGutter: true, //是否折叠
// gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"]
})
//代码自动提示功能,记住使用cursorActivity事件不要使用change事件,这是一个坑,那样页面直接会卡死
this.editor.on("keyup", function (cm, event) {
//所有的字母和'$','{','.'在键按下之后都将触发自动完成
if (!cm.state.completionActive &&
((event.keyCode >= 65 && event.keyCode <= 90 ) || event.keyCode == 52 || event.keyCode == 219 || event.keyCode == 190)) {
CodeMirror.commands.autocomplete(cm, null, {completeSingle: false});
}
});
this.hasMirror = true
},
},
其中引用是三个文件需要自己从node_modules中copy出来
index.html需引入sql_formatter.min.js
<script src="<%= BASE_URL %>static/sql_formatter.min.js"></script>
sql.js:
/** 以下是自定义的 */
var ckeywords = '';
var funwords = [];
let baseUrl = window.context.uc
console.log(baseUrl)
$.ajax({
type : "get",
url : baseUrl+ '/governance/cigResFusionTask/v1/getAllWordsForEditor',
dataType : "json",
async:false,
headers: {
'Authorization': 'Bearer ' + JSON.parse(sessionStorage.getItem('currentUser')).token
},
success: function(r){
if(r){
funwords = r.funWords;
ckeywords = sqlKeywords + r.keyWords;
window.tablewords = r.tableWords;
}
},
error : function (r){
if(r.readyState == '0' && r.status == '0'){
alert('对不起,无法连接服务器,请检查您的计算机硬件以及网络连接是否正常!');
}
}
}); if(ckeywords && ckeywords.size <=0){
ckeywords = set(sqlKeywords + "accessible action add after algorithm all analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general get global grant grants group group_concat handler hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show signal slave slow smallint snapshot soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views warnings when while with work write xa xor year_month zerofill begin do then else loop repeat");
}
CodeMirror.defineMIME("text/xl-sql", {
name: "sql",
client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
keywords: set(ckeywords),
funwords:funwords,
builtin: set("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric"),
atoms: set("false true null unknown"),
operatorChars: /^[*+\-%<>!=&|^]/,
dateSQL: set("date time timestamp"),
support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),
hooks: {
"@": hookVar,
"`": hookIdentifier,
"\\": hookClient
}
});
参考来源:https://blog.csdn.net/xiweiller/article/details/96494504
vue项目中实现sql编辑器功能自定义高亮词汇可提示关键词-codemirror的更多相关文章
- Vue项目中添加锁屏功能
0. 直接上 预览链接 Vue项目中添加锁屏功能 1. 实现思路 ( 1 ) 设置锁屏密码 ( 2 ) 密码存localStorage (本项目已经封装h5的sessionStorage和localS ...
- 如何在vue项目中使用百度编辑器ueditor
百度编辑器官方并没有提供vue项目使用说明,目前网上也有不少人实现了相关功能,这里就不再重复,只是针对自身项目碰到的情况做个记录,就当是熟悉了一遍富文本编辑器的代码结构. 按照网上的做法,基本可以实现 ...
- vue项目中导出Excel文件功能的前端代码实现
在项目中遇到了两种不同情况, 1.get请求导出文件,实现起来相对简单 // 导出数据 exportData() { window.location.href = `/oes-content-mana ...
- vue项目中实现扫码功能
项目地址:https://github.com/wkl007/vue-scan-demo.git 项目主要是做的一个扫码的功能 核心代码为 <div class="scan" ...
- 在vue项目中使用codemirror插件实现代码编辑器功能(代码高亮显示及自动提示
在vue项目中使用codemirror插件实现代码编辑器功能(代码高亮显示及自动提示) 1.使用npm安装依赖 npm install --save codemirror; 2.在页面中放入如下代码 ...
- scss/less语法以及在vue项目中的使用(转载)
1.scss与less都是css的预处理器,首先我们的明白为什么要用scss与less,因为css只是一种标记语言,其中并没有函数变量之类的,所以当写复杂的样式时必然存在局限性,不灵活,而scss与l ...
- vue项目中实现复制内容到剪贴板
项目中要实现分享功能,现在各种接口都关闭了,而且不同的浏览器要使用不同的代码,最后决定直接复制url,然后手动分享 Vue中使用了vue-clipboard2 github地址:https://git ...
- 转:如何在Vue项目中使用vw实现移动端适配
https://www.w3cplus.com/mobile/vw-layout-in-vue.html 有关于移动端的适配布局一直以来都是众说纷纭,对应的解决方案也是有很多种.在<使用Flex ...
- 如何在Vue项目中使用vw实现移动端适配(转)
有关于移动端的适配布局一直以来都是众说纷纭,对应的解决方案也是有很多种.在<使用Flexible实现手淘H5页面的终端适配>提出了Flexible的布局方案,随着viewport单位越来越 ...
- Vue项目中使用vw实现移动端适配
我们在vue移动端项目中的适配一般都采用rem,但是rem也不是能兼容所有的终端. 随着viewport单位越来越受到众多浏览器的支持,下面将简单介绍怎么实现vw的兼容问题,用vw代替rem 当我们采 ...
随机推荐
- wpf – 如何在UIElement.Margin上为绑定设置FallbackValue?
<Border BorderBrush="#cccccc" BorderThickness="1" Margin="{Binding PushM ...
- Uni-app极速入门(一) - 第一个小程序
Uni-app 介绍 官网:https://www.dcloud.io/index.html uni-app是为js开发者提供的一个全端开发框架,可以开发一次编译为web.App.小程序(微信/阿里/ ...
- React 的 KeepAlive 探索
什么是 KeepAlive? 用过 Vue 的童鞋都知道 Vue 官方自带了 Keep-Alive 组件,它能够使组件在切换时仍能保留原有的状态信息,并且有专门的生命周期方便去做额外的处理.该组件在很 ...
- 前端使用 Konva 实现可视化设计器(12)- 连接线 - 直线
这一章实现的连接线,目前仅支持直线连接,为了能够不影响原有的其它功能,尝试了2.3个实现思路,最终实测这个实现方式目前来说最为合适了. 请大家动动小手,给我一个免费的 Star 吧~ 大家如果发现了 ...
- Cygwin安装及简单说明
1 简介 官方说明:Cygwin is a Linux-like environment for Windows. It consists of a DLL (cygwin1.dll), which ...
- Java中对的创建与引用
对象与引用 Java语言中除了基本数据类型以外都属于引用类型 Java中的对象是通过引用对其操作的 class Car{ String name; String color; int price; } ...
- LeetCode 680. Valid Palindrome II 验证回文字符串 Ⅱ(C++/Java)
题目: Given a non-empty string s, you may delete at most one character. Judge whether you can make it ...
- Unity3D 内存管理非代码技巧
在场景管理器新建 gameobjct 使用代码在类初始化时 NEW 普肉fai包(包)然后将相同的类NEW够挂载到 gameobjct子节点上 在操控列表中类的时候用for循环遍历操作移动还是怎么样( ...
- 战66 WIN11 亮度热键 快捷键无效
型号:HP ZHAN 66 Pro A 14 G3. 用FN 调节音量是正常的,唯独亮度无效. 参考:怎样调节笔记本电脑屏幕亮度(惠普笔记本亮度调节快捷键失灵) | 说明书网 (shuomingshu ...
- EF 开始的片段时有问题 具有潜在运行时冲突
错误 3002: 映射从第 149 行开始的片段时有问题:表 t_Apply 的键(t_Appl .Id)具有潜在运行时冲突: 列(t_Apply .Id)映射到概念端 EntitySet t_Ap ...