使用monaco-editor编写代码编辑器

160 阅读1分钟

使用教程参考segmentfault.com/a/119000004…

1.安装插件

npm install monaco-editor -S
npm install monaco-editor-webpack-plugin -D

2.具体代码

Index.vue

<template>
  <EditorIndex ref="editorRef" class="editor-index" @blur="onCodeBlur"></EditorIndex>
</template>
<script setup>
import { ref, nextTick, onMounted } from 'vue'
import EditorIndex from './Editor.vue'

const editorRef = ref()

// 编辑器失焦事件
const onCodeBlur = (value) => {
console.log(value)
}

// 设置编辑器的值
const setEditorValue = () => {
  let editor = editorRef.value.getEditor()
  let value = `{"a": 111}`
  editorRef.value.setModelLanguage('json')
  editor.setValue(value)
  nextTick(() => {
      // 手动格式化编辑器
      editor.trigger(null, 'editor.action.formatDocument')
  })
}

onMounted(() => {
  setEditorValue()
})
</script>

Editor.vue

<template>
  <div ref="contentRef" class="content" id="content"></div>
</template>

<script setup>
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js'
import 'monaco-editor/esm/vs/basic-languages/_.contribution.js'
import { onMounted, ref } from 'vue';
// const actions = require('monaco-editor/esm/vs/editor/browser/editorExtensions.js').EditorExtensionsRegistry.getEditorActions()
// console.log(actions)

const contentRef = ref()
let editor 
const init = () => {
  editor = monaco.editor.create(contentRef.value, {
    value: '',
    language: 'json',
    theme: 'vs-dark',
    wordWrap: 'on',
    automaticLayout: true,
    autoIndent: true,
    formatOnType: true
  })
  // this.editor.onDidBlurEditorText(e => {
  //   let value = this.editor.getValue()
  // })
}
const getEditor = () => {
  return editor
}
const setModelLanguage = (lang) => {
  monaco.editor.setModelLanguage(editor.getModel(), lang);
}

onMounted(() => {
  init()
})

defineExpose({
  getEditor,
  setModelLanguage
})
</script>

<style scoped>
.content {
  width: 100%;
  height: 100%;
}
</style>