Vue codemirror realizes the effect of online code compiler

Vue codemirror realizes the effect of online code compiler

Preface

If we want to achieve the effect of online code compilation on the Web, we need to use the component vue-codemirror , which encapsulates CodeMirror again.

  • Support code highlighting
  • 62 theme colors, such as monokai, etc.
  • Supports json, sql, javascript, css, xml, html, yaml, markdown, python editing modes, the default is json
  • Support quick search
  • Support auto-completion prompts
  • Support automatic matching brackets

Environment Preparation

npm install jshint
npm install jsonlint
npm install script-loader
npm install vue-codemirror

Package components

We can encapsulate vue-codemirror again in components of the project

<template>
  <codemirror
    ref="myCm"
    v-model="editorValue"
    :options="cmOptions"
    @changes="onCmCodeChanges"
    @blur="onCmBlur"
    @keydown.native="onKeyDown"
    @mousedown.native="onMouseDown"
    @paste.native="OnPaste"
  >
  </codemirror>
</template>

<script>
import { codemirror } from "vue-codemirror";
import 'codemirror/keymap/sublime'
import "codemirror/mode/javascript/javascript.js";
import "codemirror/mode/xml/xml.js";
import "codemirror/mode/htmlmixed/htmlmixed.js";
import "codemirror/mode/css/css.js";
import "codemirror/mode/yaml/yaml.js";
import "codemirror/mode/sql/sql.js";
import "codemirror/mode/python/python.js";
import "codemirror/mode/markdown/markdown.js";
import "codemirror/addon/hint/show-hint.css";
import "codemirror/addon/hint/show-hint.js";
import "codemirror/addon/hint/javascript-hint.js";
import "codemirror/addon/hint/xml-hint.js";
import "codemirror/addon/hint/css-hint.js";
import "codemirror/addon/hint/html-hint.js";
import "codemirror/addon/hint/sql-hint.js";
import "codemirror/addon/hint/anyword-hint.js";
import "codemirror/addon/lint/lint.css";
import "codemirror/addon/lint/lint.js";
import "codemirror/addon/lint/json-lint";
import 'codemirror/addon/selection/active-line'
import "codemirror/addon/hint/show-hint.js";
import "codemirror/addon/hint/anyword-hint.js";
require("script-loader!jsonlint");
import "codemirror/addon/lint/javascript-lint.js";
import "codemirror/addon/fold/foldcode.js";
import "codemirror/addon/fold/foldgutter.js";
import "codemirror/addon/fold/foldgutter.css";
import "codemirror/addon/fold/brace-fold.js";
import "codemirror/addon/fold/xml-fold.js";
import "codemirror/addon/fold/comment-fold.js";
import "codemirror/addon/fold/markdown-fold.js";
import "codemirror/addon/fold/indent-fold.js";
import "codemirror/addon/edit/closebrackets.js";
import "codemirror/addon/edit/closetag.js";
import "codemirror/addon/edit/matchtags.js";
import "codemirror/addon/edit/matchbrackets.js";
import "codemirror/addon/selection/active-line.js";
import "codemirror/addon/search/jump-to-line.js";
import "codemirror/addon/dialog/dialog.js";
import "codemirror/addon/dialog/dialog.css";
import "codemirror/addon/search/searchcursor.js";
import "codemirror/addon/search/search.js";
import "codemirror/addon/display/autorefresh.js";
import "codemirror/addon/selection/mark-selection.js";
import "codemirror/addon/search/match-highlighter.js";
export default {
  name: "index",
  components: {codemirror},
  props: ["cmTheme", "cmMode", "cmIndentUnit", "autoFormatJson"],
  data() {
    return {
      editorValue: '{}',
      cmOptions: {
        : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : :
          "CodeMirror-lint-markers",
          "CodeMirror-linenumbers",
          "CodeMirror-foldgutter"
        ],
        highlightSelectionMatches: {
          minChars: 2,
          style: "matchhighlight",
          showToken: true
        },
      },
      enableAutoFormatJson: this.autoFormatJson == null ? true : this.autoFormatJson, // In json editing mode, whether to automatically format when the input box loses focus, true to enable, false to disable}
  },
  created() {
    try {
      if (!this.editorValue) {
        this.cmOptions.lint = false;
        return;
      }
      if (this.cmOptions.mode === "application/json") {
        if (!this.enableAutoFormatJson) {
          return;
        }
        this.editorValue = this.formatStrInJson(this.editorValue);
      }
    } catch (e) {
      console.log("Error in initializing codemirror: " + e);
    }
  },
  methods: {
    resetLint() {
      if (!this.$refs.myCm.codemirror.getValue()) {
        this.$nextTick(() => {
          this.$refs.myCm.codemirror.setOption("lint", false);
        });
        return;
      }
      this.$refs.myCm.codemirror.setOption("lint", false);
      this.$nextTick(() => {
        this.$refs.myCm.codemirror.setOption("lint", true);
      });
    },
    //Format string as json format string formatStrInJson(strValue) {
      return JSON.stringify(
        JSON.parse(strValue),
        null,
        this.cmIndentUnit
      );
    },
    onCmCodeChanges(cm, changes) {
      this.editorValue = cm.getValue();
      this.resetLint();
    },
    // Handling function when losing focus onCmBlur(cm, event) {
      try {
        let editorValue = cm.getValue();
        if (this.cmOptions.mode === "application/json" && editorValue) {
          if (!this.enableAutoFormatJson) {
            return;
          }
          this.editorValue = this.formatStrInJson(editorValue);
        }
      } catch (e) {
        // Do nothing}
    },
    //Keyboard event processing function onKeyDown(event) {
      const keyCode = event.keyCode || event.which || event.charCode;
      const keyCombination =
          event.ctrlKey || event.altKey || event.metaKey;
      if (!keyCombination && keyCode > 64 && keyCode < 123) {
        this.$refs.myCm.codemirror.showHint({ completeSingle: false });
      }
    },
    //Event processing function when the mouse is pressed onMouseDown(event) {
      this.$refs.myCm.codemirror.closeHint();
    },
    // Paste event processing function OnPaste(event) {
      if (this.cmOptions.mode === "application/json") {
        try {
          this.editorValue = this.formatStrInJson(this.editorValue);
        } catch (e) {
          // Do nothing}
      }
    },
  }
}
</script>

<style scoped>

</style>

This component is configured with a json compiler by default. cmOptions contains configuration items for the code compiler. If you need additional functions, you can also refer to the official documentation configuration. Next, see the display effect

You can see that we entered a string in json format. Even if the format is incorrect, we will get an error message and it will automatically format it for us.

Python Compiler

The component we encapsulate is a json compiler by default. If we want to use other languages, it is also very simple. We just need to import the mode of other languages.

<template>
  <div>
    <el-button type="primary" icon="el-icon-circle-check-outline" @click="handleConfirm" round>
      Click Save</el-button>
    <el-button icon="el-icon-caret-right" type="info" @click="handleRunCode" round>
      Run online</el-button>
  <code-editor
    :cmTheme="cmTheme"
    :cmMode="cmMode"
  >
  </code-editor>
  </div>
</template>

<script>
import codeEditor from '@/components/CodeEditor/index'
import 'codemirror/theme/monokai.css' // Import the monokai theme import 'codemirror/mode/python/python.js' // Import python
export default {
  name: "index",
  components:
    codeEditor
  },
  data() {
    return {
      cmTheme: "monokai",
      cmMode: "python",
    }
  },
  methods: {
    handleConfirm() {},
    handleRunCode() {}
  }
}
</script>

<style>
.CodeMirror {
  position: relative;
  height: 100vh;
  overflow: hidden;
  margin-top: 10px;
}
</style>
<style lang="scss" scoped>
</style>

The effect is as follows

This is the end of this article about vue codemirror's implementation of online code compiler. For more relevant vue codemirror online code compiler content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue implements SQL code formatting function in codemirror code editor
  • Use the codemirror plugin to implement code editor function in vue project
  • Two ways to use codemirror in Vue
  • Problems encountered when using codemirror in vue
  • Detailed example of using codemirror in vue
  • Use Vue Demi to build a component library compatible with both Vue2 and Vue3

<<:  Summary of all HTML interview questions

>>:  Docker-compose installation yml file configuration method

Recommend

HTML/CSS Basics - Several precautions in HTML code writing (must read)

The warning points in this article have nothing t...

Practical record of Vue3 combined with TypeScript project development

Table of contents Overview 1. Compositon API 1. W...

Steps to deploy multiple tomcat services using DockerFile on Docker container

1. [admin@JD ~]$ cd opt #Enter opt in the root di...

Using HTML+CSS to track mouse movement

As users become more privacy-conscious and take m...

Detailed explanation of two quick ways to write console.log in vscode

(I) Method 1: Define it in advance directly in th...

10 tips for designing useful, easy-to-use web applications

Here are 10 tips on how to design better-usable w...

Using nginx + fastcgi to implement image recognition server

background A specific device is used to perform i...

Example of how to embed H5 in WeChat applet webView

Preface WeChat Mini Programs provide new open cap...

Detailed explanation of the pitfalls of nginx proxy socket.io service

Table of contents Nginx proxies two socket.io ser...

Master-slave synchronization configuration of Mysql database

Table of contents Mysql master-slave synchronizat...

MySQL 5.7.17 installation and use graphic tutorial

MySQL is a relational database management system ...