vue2.x 使用monaco-editor 组件 详细教程

vue2.x 使用monaco-editor 组件 详细教程

代码内容直接参考下方引用资料内的;有需要就按照类似的思路去自定义。。。。

其中需要格式化代码的地方需要注意下,不加延迟无效

必须加延迟

必须加延迟

必须加延迟

大概如下:

changeEditor() {
      if (this.editor === null) {
        this.init()
      }

      const oldModel = this.editor.getModel()
      const newModel = monaco.editor.createModel(this.code, 'javascript')

      if (oldModel) {
        oldModel.dispose()
      }
      this.editor.setModel(newModel)
     // 若需要代码格式化必须加个延迟生效
     setTimeout(() => {
          this.format()
        }, 300)
}

原文教程复制备份

安装

指定版本安装(版本过高容易报错)

npm install monaco-editor@0.30.1 --save-dev
npm install monaco-editor-webpack-plugin@6.0.0 --save-dev

配置

vue.config.js中配置 monaco-editor-webpack-plugin 

const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin')
module.exports = {
  configureWebpack: {
    plugins: [
      new MonacoWebpackPlugin()
    ]
  }
}

创建MonacoEditor公共组件

<template>
  <div ref="editor" class="editor"></div>
</template>
 
<script>
import * as monaco from 'monaco-editor';
export default {
  name: 'MonacoEditor',
  data() {
    return {
      code: '',
      editor: null
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      // 初始化编辑器
      this.editor = monaco.editor.create(this.$refs.editor, {
        value: this.code,
        language: 'javascript',
        tabSize: 2,
        scrollBeyondLastLine: false,
        automaticLayout: true, // 自动布局
        readOnly: false
      })
      console.log(this.editor)
 
      // 监听内容变化
      this.editor.onDidChangeModelContent(() => {
 
      })
 
      // 监听失去焦点事件
      this.editor.onDidBlurEditorText((e) => {
        console.log(e)
      });
    },
    // 获取编辑框内容
    getCodeContext() {
      return this.editor.getValue()
    },
    // 自动格式化代码
    format() {
      this.editor.trigger('anything', 'editor.action.formatDocument')
      // 或者
      // this.editor.getAction(['editor.action.formatDocument']).run()
      //或者
      //自定义格式化 后赋值
    },
    changeEditor() {
      if (this.editor === null) {
        this.init()
      }
 
      const oldModel = this.editor.getModel()
      const newModel = monaco.editor.createModel(
        this.code,
        'sql'
      )
 
      if (oldModel) {
        oldModel.dispose()
      }
      this.editor.setModel(newModel)
    }
  }
}
</script>
 
<style scoped>
.editor {
  width: 100%;
  min-height: 100%;
}
</style>

父组件使用

<template>
  <div>
    <monaco-editor></monaco-editor>
  </div>
</template>
 
<script>
import MonacoEditor from '@/components/MonacoEditor'
export default {
  name: 'Father',
  components: {
    MonacoEditor
  }
 
}
</script>

引用资料

1. monaco-editor vue2.X组件化

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值