天天看點

vue 使用 monaco-editor 實作線上編輯器

前言

項目裡使用到 monaco-editor 編輯器,實作源碼編輯器,看了很多網上教程,記錄一下實作過程。在此之前引用很多部落客的方法安裝但是引入的時候,運作項目總是各種各樣的錯誤,找不到頭緒。終于在搜尋文章的時候,看到裡面的運作錯誤我也遇到過:來源

vue 使用 monaco-editor 實作線上編輯器

看到下面的評論,我也嘗試着安裝,版本号對應上就可以實作了。

vue 使用 monaco-editor 實作線上編輯器

話不多說,直接上代碼.

安裝

使用 npm 安裝對應版本号

"monaco-editor": "0.27.0",
"monaco-editor-webpack-plugin": "4.2.0"
           

使用

import * as monaco from "monaco-editor";
           

子元件

<template>
  <div ref="main" style="width: 100%; height: 300px"></div>
</template>

<script>
import * as monaco from "monaco-editor";

export default {
  data() {
    return {
      monacoEditor: null,
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      // 使用 - 建立 monacoEditor 對象
      this.monacoEditor = monaco.editor.create(this.$refs.main, {
        theme: "vs-dark", // 主題
        value: "console.log(1111)", // 預設顯示的值
        language: "javascript",
        folding: true, // 是否折疊
        foldingHighlight: true, // 折疊等高線
        foldingStrategy: "indentation", // 折疊方式  auto | indentation
        showFoldingControls: "always", // 是否一直顯示折疊 always | mouseover
        disableLayerHinting: true, // 等寬優化
        emptySelectionClipboard: false, // 空選擇剪切闆
        selectionClipboard: false, // 選擇剪切闆
        automaticLayout: true, // 自動布局
        codeLens: false, // 代碼鏡頭
        scrollBeyondLastLine: false, // 滾動完最後一行後再滾動一螢幕
        colorDecorators: true, // 顔色裝飾器
        accessibilitySupport: "off", // 輔助功能支援  "auto" | "off" | "on"
        lineNumbers: "on", // 行号 取值: "on" | "off" | "relative" | "interval" | function
        lineNumbersMinChars: 5, // 行号最小字元   number
        enableSplitViewResizing: false,
        readOnly: false, //是否隻讀  取值 true | false
      });
    },
  },
};
</script>
           

父元件

<template>
  <div>
    <monaco-editor></monaco-editor>
  </div>
</template>

<script>
  import monacoEditor from './components/index.vue';
  export default{
     components:{
        monacoEditor
     }
  }
</script>
           

實作效果

vue 使用 monaco-editor 實作線上編輯器

最終的實作效果裡我發現的功能有:

  • 代碼提示
  • 代碼高亮
  • 右鍵有菜單
vue 使用 monaco-editor 實作線上編輯器
  • 代碼搜尋
vue 使用 monaco-editor 實作線上編輯器

其他配置

代碼提示

根據上面的步驟引入調用後,是有代碼提示的,效果如下:

vue 使用 monaco-editor 實作線上編輯器

重點來了!!!!

我在 vue.config.js 裡配置了以下代碼,代碼提示一下子多了起來。

const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');

module.exports = {
   configureWebpack: {
      plugins: [
         new MonacoWebpackPlugin()
      ]
   }
};
           
vue 使用 monaco-editor 實作線上編輯器

示例

完成以上的使用和配置後,接下來就可以實作一個線上編輯器了,運作代碼部分查詢資料,借鑒了這個部落客的 文章

<template>
  <div id="app" class="flex-row">
    <div class="left-content">
      <div class="flex-row">
        <div class="wrap">
          <p style="background: #6aa84f">html</p>
          <monaco-edito
            ref="html"
            width="500px"
            height="290px"
            language="html"
            ></monaco-edito>
        </div>
        <div class="wrap">
          <p style="background: #cc4125">css</p>
          <monaco-edito
            ref="css"
            width="500px"
            height="290px"
            language="css"
            ></monaco-edito>
        </div>
      </div>
      <div class="wrap">
        <p style="background: #f1c232">js</p>
        <monaco-edito ref="js" height="260px"></monaco-edito>
      </div>
    </div>
    <div class="right-content">
      <button @click="runCode">運作</button>
      <p>實作結果:</p>
      <iframe class="view-panel" id="preview" frameborder="0"></iframe>
    </div>
  </div>
</template>

<script>
  import MonacoEdito from "./components/monaco-editor.vue";
  
  export default {
    name: "app",
    components: {
      MonacoEdito,
    },
    methods: {
      runCode() {
        var html = this.$refs.html.monacoEditor.getValue();
        var css = this.$refs.css.monacoEditor.getValue();
        var js = this.$refs.js.monacoEditor.getValue();
        let code = `
        <!DOCTYPE html>
        <html lang="en">
        <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Editor</title>
        <style>${css}</style>
        </head>
        <body>${html}</body>
        <script>${js}<\/script>
        </html>
       `;
        console.log(code);
        const preview = document.getElementById("preview");
        preview.setAttribute("srcdoc", code);
      },
    },
  };
</script>

<style>
  * {
    padding: 0;
    margin: 0;
  }
  .flex-row {
    display: flex;
    flex-direction: row;
  }
  .result {
    border: 1px solid #ccc;
    width: 100%;
    height: 500px;
  }
  .left-content {
    width: 1000px;
  }
  .right-content {
    margin-left: 15px;
    padding: 10px;
    width: 100%;
  }
  .wrap {
    display: flex;
    flex-direction: column;
  }
  .wrap p {
    padding: 5px;
    text-align: center;
    font-size: 18px;
    font-weight: bold;
    color: #fff;
  }
  .right-content p {
    margin: 5px 0;
  }
  button {
    display: inline-block;
    line-height: 1;
    white-space: nowrap;
    cursor: pointer;
    background: #409eff;
    border: 1px solid #409eff;
    color: #ffffff;
    -webkit-appearance: none;
    text-align: center;
    box-sizing: border-box;
    outline: none;
    margin: 0;
    transition: 0.1s;
    font-weight: 500;
    padding: 12px 20px;
    font-size: 14px;
    border-radius: 4px;
  }
</style>
           

還要配置下 vue.config.js

const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');

module.exports = {
    configureWebpack: {
        plugins: [
            new MonacoWebpackPlugin({ languages: ['javascript', 'typescript', 'html', 'css', 'json'] })
        ]
    }
};
           

實作效果

vue 使用 monaco-editor 實作線上編輯器

源碼位址

https://gitee.com/dyclown/vue-monaco-editor-demo