sql编辑器一些配置项

(更多配置项参考:https://blog.csdn.net/JLU_Lei/article/details/80259697)
在这里插入图片描述
在这里插入图片描述

事件监听

触发器使用方法: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”硬件事件触发器

下面详细记录vue导入sql编辑器进行sql编写的方法


# API 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():刷新编辑器/n this.CodeMirrorEditor.execCommand(“命令”):执行命令

效果图

在这里插入图片描述

一、下载sql编辑器插件

npm install --save sql-formatter
npm install --save vue-codemirror 

二、使用步骤

1.引入

父组件
在这里插入图片描述
子组件

import "codemirror/theme/ambiance.css";
import "codemirror/lib/codemirror.css";
import "codemirror/addon/hint/show-hint.css";
let CodeMirror = require("codemirror/lib/codemirror");
require("codemirror/addon/edit/matchbrackets");
require("codemirror/addon/selection/active-line");
require("codemirror/mode/sql/sql");
require("codemirror/addon/hint/show-hint");
require("codemirror/addon/hint/sql-hint");

2.vue文件(父和子)

父组件:

<template>
  <div class="history-container">
            <span class="btn2">
              <el-button
                @click="showBtn"
                style="
                  background-color: #fff;
                  color: #1192ac;
                  font-size: 14px;
                  height: 40px;
                  padding: 0px 8px;
                "
                size="small"
                >点击显示对话框</el-button
              >
            </span>
    <el-dialog
      @close="cancelScheduleInfoDia"
      :title="title"
      top="160px"
      width="400px;"
      :close-on-click-modal="false"
      :visible.sync="visible"
      class="planDialog"
    >
      <el-form
        ref="addRecordFormRef"
        :rules="addRecordFormRules"
        :model="addRecordForm"
        :label-position="labelPosition"
        label-width="110px"
        class="firstform"
      >
        <el-form-item label="查询名称:" prop="statisticsName">
          <el-input
            v-model="addRecordForm.statisticsName"
            placeholder="请选择"
            class="selcClass timesel"
            style="width: 100%"
            filterable
            @change="statisticsNameIpt"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="SQL脚本:" prop="sqlcontent">
          <el-tag
            type="warning"
            style="position: absolute; top: 35px; left: -75px; cursor: pointer"
            @click="formatterBtn"
            >格式化</el-tag
          >
          <SqlEditor
            v-if="sqlVisible"
            ref="sqleditor"
            :value="addRecordForm.sqlcontent"
            :tables="sqlTable"
            @changeTextarea="changeTextarea($event)"
          />
          <!-- <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            style="width: 100%"
            v-model="addRecordForm.sqlcontent"
          /> -->
        </el-form-item>
        <el-form-item label="备注:" prop="remark">
          <el-input
            v-model="addRecordForm.remark"
            placeholder="请选择"
            class="selcClass timesel"
            style="width: 100%"
            filterable
          >
          </el-input>
        </el-form-item>
        <el-form-item label="排序:" prop="serialNo">
          <el-input
            v-model="addRecordForm.serialNo"
            placeholder="请选择"
            class="selcClass timesel"
            style="width: 100%"
            filterable
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div class="myBtn text-align_right">
        <el-button @click="cancle">取消</el-button>
        <el-button type="primary" @click="addSure">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import sqlFormatter from 'sql-formatter'
import SqlEditor from '@/components/SqlEditor'
export default {
  components: { SqlEditor },
  data() {
    return {
      sqlVisible: true,
      sqlTable: {},
      addRecordFormRules: {
        statisticsName: [{ required: true, message: '请输入查询名称', trigger: 'blur' },],
        sqlcontent: [{ required: true, message: '请输入SQL脚本', trigger: 'blur' },],
        remark: [{ required: true, message: '请输入备注', trigger: 'blur' },],
        serialNo: [{ required: true, message: '请输入排序', trigger: 'blur' },],
      },
      addRecordForm: {
        statisticsName: '',
        sqlcontent: '',
        remark: "",
        serialNo: '',
        statisticsId: '',
      },
      labelPosition: 'right',
    }
  },
  methods: {
 //实时记录sql输入变化
    changeTextarea(val) {
      this.addRecordForm.sqlcontent = val;
    },
    //格式化 输入的sql语句
    formatterBtn(val) {
      let dom = this.$refs.sqleditor
      dom.editor.setValue(sqlFormatter.format(dom.editor.getValue()))
    },
    editLeftTree() {
      this.sqlVisible= true
      //回显sql
      this.$nextTick(() => {
        const dom = this.$refs.sqleditor;
        dom.editor.setValue(this.sqljb);
      });
    },
    cancle() {
      this.sqlVisible= false
      this.$refs.addRecordFormRef.resetFields()
    },
    cancelScheduleInfoDia() {
      this.sqlVisible= false
      this.$refs.addRecordFormRef.resetFields()
    }
  },
}
</script>

<style lang="scss" scoped>
</style>

子组件:

<template>
  <div>
    <textarea ref="sqlEditor" v-model="value" class="codesql"></textarea>
  </div>
</template>
<script>
import "codemirror/theme/ambiance.css";
import "codemirror/lib/codemirror.css";
import "codemirror/addon/hint/show-hint.css";
let CodeMirror = require("codemirror/lib/codemirror");
require("codemirror/addon/edit/matchbrackets");
require("codemirror/addon/selection/active-line");
require("codemirror/mode/sql/sql");
require("codemirror/addon/hint/show-hint");
require("codemirror/addon/hint/sql-hint");
export default {
  name:'SqlEditor',
  data() {
    return {
      editor: null
    }
  },
    props: {
      // 接收父组件传值
      value: {
        type: String,
        default: ''
      },
      sqlStyle: {
        type: String,
        default: 'default'
      },
      readOnly: {
        type: [Boolean, String]
      },
      // 父组件将表结构传给编辑器,实现自动提示表名和字段名的功能
      tables: {
        type: Object,
        default: () => { }
      }
  },
  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('');
        }
      }
    }
  },
  computed: {
    newVal() {
      if (this.editor) {
        return this.editor.getValue();
      }
    }

  },

  mounted() {
    let mime = 'text/x-mariadb'
    //let theme = 'ambiance'//设置主题,不设置的会使用默认主题
    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
      }
    });
    //代码自动提示功能,记住使用cursorActivity事件不要使用change事件,这是一个坑,那样页面直接会卡死==编辑器触发
    this.editor.on('inputRead', () => {
      this.editor.showHint()
    })
  },
  methods: {
    setVal() {
      if (this.editor) {
        if (this.value === '') {
          this.editor.setValue('')
        } else {
          this.editor.setValue(this.value)
        }

      }
    }
  }
}
</script>
<style>
.CodeMirror {
  color: black;
  direction: ltr;
  line-height: 22px;
}
.CodeMirror-hints {
  z-index: 9999 !important;
}
</style>

Logo

前往低代码交流专区

更多推荐