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

In-depth analysis of MySQL execution plans

Preface In the previous interview process, when a...

MySQL single table query example detailed explanation

1. Prepare data The following operations will be ...

Talk about the 8 user instincts behind user experience in design

Editor's note: This article is contributed by...

Solution to MySQL IFNULL judgment problem

Problem: The null type data returned by mybatis d...

Design theory: On the issues of scheme, resources and communication

<br />This problem does not exist in many sm...

React error boundary component processing

This is the content of React 16. It is not the la...

mysql query data for today, this week, this month, and last month

today select * from table name where to_days(time...

Two methods of restoring MySQL data

1. Introduction Some time ago, there were a serie...

Use the sed command to modify the kv configuration file in Linux

sed is a character stream editor under Unix, that...

Vue data two-way binding implementation method

Table of contents 1. Introduction 2. Code Impleme...

Detailed explanation of the data responsiveness principle of Vue

This article is mainly for those who do not under...

3D tunnel effect implemented by CSS3

The effect achievedImplementation Code html <d...