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

How to make a List in CocosCreator

CocosCreator version: 2.3.4 Cocos does not have a...

How to smoothly upgrade and rollback Nginx version in 1 minute

Today, let's talk about a situation that is o...

Five practical tips for web form design

1. Mobile selection of form text input: In the te...

How to view the IP address of Linux in VMware virtual machine

1. First, double-click the vmware icon on the com...

Detailed explanation of MySql installation and login

Check if MySQL is already installed in Linux sudo...

Mini Program to Implement Text Circular Scrolling Animation

This article shares the specific code of the appl...

Problems and solutions of using TweenMax animation library in angular

I have nothing to do recently, so I tinker with C...

MySQL scheduled database backup operation example

This article describes the example of MySQL sched...

Node uses async_hooks module for request tracking

The async_hooks module is an experimental API off...

8 ways to manually and automatically backup your MySQL database

As a popular open source database management syst...

MySQL 5.7.18 Green Edition Download and Installation Tutorial

This article records the detailed process of down...

Analysis of MySQL multi-table joint query operation examples

This article describes the MySQL multi-table join...