vue中使用monaco-editor

monaco-editor是一款代码编辑器,使用它我们可以再web实现vscode的基本功能,下面是在vue中使用monaco-editor流程
安装

npm install monaco-editor monaco-editor-webpack-plugin

vue.config.js配置
  这里我只添加了针对js的代码提示,如果只填写js的代码提示会发现并没有左右,后来在monaco-editor-webpack-plugin的介绍中发现了端倪:

vue中使用monaco-editor_第1张图片
就是说添加js的语法提示必须依赖ts,所以必须把ts也加上

chainWebpack: (config) => {
    config.plugin("monaco-editor").use(new MonacoWebpackPlugin({
      languages: ["javascript","typescript"],
    }));
  },

在组件中使用

import * as monaco from "monaco-editor/esm/vs/editor/edcore.main"; // 引入monaco-editor
export default {
  name: "monacoEditor",
  props: {
    editorOptions: {
      type: Object,
      default: function () {
        return {
          selectOnLineNumbers: true,
          roundedSelection: false,
          readOnly: true, // 只读
          cursorStyle: "line", //光标样式
          automaticLayout: false, //自动布局
          glyphMargin: true, //字形边缘
          useTabStops: false,
          fontSize: 28, //字体大小
          autoIndent: true, //自动布局
          quickSuggestionsDelay: 500, //代码提示延时
          language: "javascript", //语言
        };
      },
    },
    codes: {
      type: String,
      default: function () {
        return ``
};
        `;
      },
    },
  },
  data() {
    return {
      editor: null,
    };
  },
  mounted() {
    this.initEditor();
  },
  methods: {
    initEditor() {
      const self = this;
      // 初始化编辑器,确保dom已经渲染
      this.editor = monaco.editor.create(self.$refs.monaco, {
        value: self.codeValue || self.codes, // 编辑器初始显示内容
        language: "javascript", // 支持语言
        theme: "vs", // 主题
        selectOnLineNumbers: true, //显示行号
        editorOptions: self.editorOptions,// 编辑器配置
        noSemanticValidation: true,// 不显示语法错误
      });
      //监测窗口变化
      window.addEventListener("resize", function () {
        self.editor.layout();
      });
    },
  },
};

html代码

<template>
  <div id="monaco-editor-box">
    <div id="monaco-editor" ref="monaco"></div>
  </div>
</template>

然后就可以在web端使用了.

你可能感兴趣的:(vue,vue.js,javascript,前端)