monaco-editor

1,330 阅读1分钟

安装插件(注意版本)官方文档

"monaco-editor": "^0.28.1",
"monaco-editor-webpack-plugin": "^4.2.0",

对应的版本

monaco-editor-webpack-pluginmonaco-editor
7.*.*>= 0.31.0
6.*.*0.30.*
5.*.*0.29.*
4.*.*0.25.*0.26.*0.27.*0.28.*
3.*.*0.22.*0.23.*0.24.*
2.*.*0.21.*
1.9.*0.20.*
1.8.*0.19.*
1.7.*0.18.*

配置vue.coinfig.js

const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
chainWebpack: (config) => {
    config.plugin('monaco').use(new MonacoWebpackPlugin());
  },

简单使用

  1. id使用动态是因为要动态创建多个对象
  2. 别使用ref获取dom数组,根据索引确定具体dom,删除时很麻烦.
  3. 简单实现
<template>
    <div ref="container" :id="'container_' + value.index" style="height: 100%; min-height: 560px"></div>
</template>
<script>
import * as monaco from 'monaco-editor';
export default {
  name: 'opendir',
  data() {
    return {
      modals: false, //编辑器开关
      editor: '', //当前编辑器对象
      editorIndex: [
        //选项卡数组
        {
          tab: true,
          index: '0',
          title: '',
          icon: '',
        },
      ],
      editorList: [], //编辑器数组
      indexEditor: 0, //当前编辑器索引
    };
  },
  mounted() {
    this.initEditor();
  },
  computed: {},
  methods: {
    /**
     * 初始化编辑器
     */
    initEditor() {
      let that = this;
      //动态创建使用nextTick函数,非动态请忽略
      that.$nextTick(() => {
        // 初始化编辑器,确保dom已经渲染
        that.editor = monaco.editor.create(document.getElementById('container_' + that.indexEditor), {
          value: that.code, //编辑器初始显示文字
          language: 'sql', //语言支持自行查阅demo
          automaticLayout: true, //自动布局
          theme: 'vs', //官方自带三种主题vs, hc-black, or vs-dark
          foldingStrategy: 'indentation', // 代码可分小段折叠
          overviewRulerBorder: false, // 不要滚动条的边框
          scrollbar: {
            // 滚动条设置
            verticalScrollbarSize: 4, // 竖滚动条
            horizontalScrollbarSize: 10, // 横滚动条
          },
          autoIndent: true, // 自动布局
          tabSize: 4, // tab缩进长度
          autoClosingOvertype: 'always',
        });
        //添加按键监听
        that.editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_S, function () {
          //自定义保存方法....
        });
        that.editor.onKeyUp(() => {
          // 当键盘按下,判断当前编辑器文本与已保存的编辑器文本是否一致
          if (that.editor.getValue() != that.code) {
            // 自定义操作
          }
        });
        that.editorList.push({
          editor: that.editor,
          oldCode: that.code,
          path: '',
          isSave: true,
          index: that.indexEditor,
        });
      });
    },
    /**
     * 切换语言
     * @param {Object} mode
     */
    changeModel(mode, value) {
      var oldModel = this.editorList[this.indexEditor].editor.getModel(); //获取旧模型
      // var value = this.editor.getValue();//获取旧的文本
      //创建新模型,value为旧文本,id为modeId,即语言(language.id)
      //modesIds即为支持语言
      // var modesIds = monaco.languages.getLanguages().map(function(lang) { return lang.id; });
      if (!mode) mode = oldModel.getLanguageId();
      // if(!value) value = this.editor.getValue();

      var newModel = monaco.editor.createModel(value, mode);
      //将旧模型销毁
      if (oldModel) {
        oldModel.dispose();
      }
      //设置新模型
      this.editorList[this.indexEditor].editor.setModel(newModel);
    },
  },
};
</script>

支持的语言类型

['plaintext', 'json', 'abap', 'apex', 'azcli', 'bat', 'cameligo', 'clojure', 'coffeescript', 'c', 'cpp', 'csharp', 'csp', 'css', 'dart', 'dockerfile', 'fsharp', 'go', 'graphql', 'handlebars', 'hcl', 'html', 'ini', 'java', 'javascript', 'julia', 'kotlin', 'less', 'lexon', 'lua', 'markdown', 'mips', 'msdax', 'mysql', 'objective-c', 'pascal', 'pascaligo', 'perl', 'pgsql', 'php', 'postiats', 'powerquery', 'powershell', 'pug', 'python', 'r', 'razor', 'redis', 'redshift', 'restructuredtext', 'ruby', 'rust', 'sb', 'scala', 'scheme', 'scss', 'shell', 'sol', 'aes', 'sql', 'st', 'swift', 'systemverilog', 'verilog', 'tcl', 'twig', 'typescript', 'vb', 'xml', 'yaml']

创建差异编辑器

  1. 简单实现
//html
<div id="container" style="height: 100%"></div>
//js
var originalModel = monaco.editor.createModel('heLLo world!', 'text/plain');
var modifiedModel = monaco.editor.createModel('hello orlando!', 'text/plain');

var diffEditor = monaco.editor.createDiffEditor(document.getElementById('container'));
diffEditor.setModel({
	original: originalModel,
	modified: modifiedModel
});
  1. 效果 image.png