vue2.0項目使用spl-formatter 和 codemirror實現sql語句格式化


簡介:Pc后台需要展示sql語句

一、下載兩個插件

1. npm install sql-formatter --save

2.npm install codemirror --save

二、在components中創建文件來存放sql這個功能,哪里需要哪里搬

復制以下代碼到文件里

<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";
import "codemirror/theme/monokai.css";
// 引入全局實例
const CodeMirror = require("codemirror/lib/codemirror");
const sqlformatter = require("sql-formatter");
//
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");

export default {
  name: "SqlEditor",
  props: {
    // 接收父組件傳值
    value: {
      type: String,
      default: ""
    },
    sqlStyle: {
      type: String,
      default: "default"
    },
    readOnly: {
      type: [Boolean, String]
    },
    // 父組件將表結構傳給編輯器,實現自動提示表名和字段名的功能
    tables: {
      type: Object,
      default: () => {}
    },
    editorHeight: {
      type: Number,
      default: 450
    },
    tableInfo: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      editor: null
    };
  },
  computed: {
    // 將編輯器中的值賦給newVal變量
    newVal() {
      if (this.editor) {
        return this.editor.getValue();
      } else {
        return "";
      }
    }
  },
  watch: {
    // 監聽newVal值的變化,通過getValue方法獲取到值並傳遞給父組件
    newVal() {
      // console.log(newV, oldV)
      if (this.editor) {
        this.$emit("changeTextarea", this.editor.getValue());
      }
    },
    // 將value賦值給編輯器配置項改變值中的value
    value(newV) {
      //
      // console.log("### 新值" + newV)
      // console.log("### 舊值" + oldV)
      if (this.editor) {
        let cursor = this.editor.doc.getCursor();
        if (newV === "") {
          this.editor.setValue("");
          this.editor.setCursor(cursor);
        } else {
          this.editor.setValue(newV);
          this.editor.setCursor(cursor);
        }
      }
    },
    // tableInfo(val) {
    //   if(val) {
    //     let getCursor = this.editor.doc.getCursor()
    //     let pos = {};
    //     pos.line = getCursor.line;
    //     pos.ch = getCursor.ch;
    //     this.editor.doc.replaceRange(" "+ val +" ",pos)
    //   }
    // },
    // 根據父組件中的高度來給editor動態設置高度
    editorHeight(newV) {
      this.editor.setSize("100%", newV);
    }
  },
  mounted() {
    this.editor = CodeMirror.fromTextArea(this.$refs.sqlEditor, {
      // value: this.value,
      mode: { name: "text/x-hive" },
      indentWithTabs: true,
      smartIndent: true,
      lineNumbers: true,
      matchBrackets: true,
      cursorHeight: 1,
      lineWrapping: true,
      readOnly: this.readOnly,
      theme: "monokai",
      autofocus: true,
      extraKeys: {
        "'a'": this.completeAfter,
        "'b'": this.completeAfter,
        "'c'": this.completeAfter,
        "'d'": this.completeAfter,
        "'e'": this.completeAfter,
        "'f'": this.completeAfter,
        "'g'": this.completeAfter,
        "'h'": this.completeAfter,
        "'i'": this.completeAfter,
        "'j'": this.completeAfter,
        "'k'": this.completeAfter,
        "'l'": this.completeAfter,
        "'m'": this.completeAfter,
        "'n'": this.completeAfter,
        "'o'": this.completeAfter,
        "'p'": this.completeAfter,
        "'q'": this.completeAfter,
        "'r'": this.completeAfter,
        "'s'": this.completeAfter,
        "'t'": this.completeAfter,
        "'u'": this.completeAfter,
        "'v'": this.completeAfter,
        "'w'": this.completeAfter,
        "'x'": this.completeAfter,
        "'y'": this.completeAfter,
        "'z'": this.completeAfter,
        "'.'": this.completeAfter,
        "Ctrl-Alt-L": this.format
      }
      //   hintOptions: {
      //     tables: this.dataBaseTips,
      //   },
    });

    this.editor.setSize("100%", this.editorHeight);
    // 監聽inputRead事件,實現代碼自動提示功能

    // 監聽光標事件,獲取光標選中的內容
    this.editor.on("cursorActivity", () => {
      // this.editor.showHint();
      let somethingSelected = this.editor.doc.somethingSelected(); //是否有光標選中內容
      let getSelection = this.editor.doc.getSelection(); //光標選中內容
      this.$emit("getSelectContent", somethingSelected, getSelection);
    });

    // this.editor.on("keyup", function (cm ,e) {
    //   var arrows = [37, 38, 39, 40];
    //   if (arrows.indexOf(e) < 0) {
    //     this.editor.execCommand("autocomplete")
    //   }
    // });
  },

  methods: {
    tableInfoChange(val) {
      if (val) {
        let getCursor = this.editor.doc.getCursor();
        let pos = {};
        pos.line = getCursor.line;
        pos.ch = getCursor.ch;
        this.editor.doc.replaceRange(" " + val + " ", pos);
      }
    },
    completeAfter(cm, pred) {
      if (!pred || pred())
        setTimeout(function() {
          if (!cm.state.completionActive)
            cm.showHint({
              completeSingle: false
            });
        }, 100);
      return CodeMirror.Pass;
    },

    format() {
      let sqlcontent = this.editor.getValue();
      this.editor.setValue(sqlformatter.format(sqlcontent));
      let cursor = this.editor.doc.getCursor();
      this.editor.setCursor(cursor);
    }
  }
};
</script>

<style scope>
.CodeMirror {
  height: auto;
  /* height: 450px!important; */
  /* width: 900px!important; */
}
.CodeMirror-cursors {
  visibility: visible !important;
  animation: cursorActive 1s infinite steps(1, start);
}
.cm-s-monokai .CodeMirror-cursor {
  border-left: 2px solid #d5690f !important;
}
@keyframes cursorActive {
  0%,
  100% {
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
}
</style>
三、在頁面引入這個components中存放sql的文件

 

 四、在頁面中調用這個組件

 

 

 

 五、效果展示

 

 六、說明

組件里面的value,賦值給它什么值就展示什么,sql的內容可刪除可復制,還可自己寫sql語句


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM