Vite管理的Vue3项目中monaco editer的使用以及组件封装

文章目录

背景

做oj系统的时候,需要使用代码编辑器,决定使用Monaco Editor,但是因为自身能力问题,读不懂官网文档,最终结合ai和网友的帖子成功引入,并封装了组件,支持v-model接收文档内容。希望可以帮助到别人。

环境说明

  • vite
  • vue3
  • pnpm

安装流程以及组件封装

引入依赖

shell 复制代码
pnpm install monaco-editor

封装组件

vue 复制代码
<script setup lang="ts">
import * as monaco from 'monaco-editor'
import { onMounted, ref } from 'vue'


// 容器对象
const editorContainer = ref()

// 编辑器对象
let codeEditor: monaco.editor.IStandaloneCodeEditor | null = null

// 声明一个input事件
const emit = defineEmits(['update:modelValue'])

// 从父组件中接收
const props = defineProps({
  language: {
    type: String,
    default: 'javascript'
  },
  modelValue: {
    type: String,
    default: '',
    required: true
  }
})

onMounted(() => {
  codeEditor = monaco.editor.create(editorContainer.value, {
    value: props.modelValue,
    language: props.language,
    lineNumbers: "on",
    roundedSelection: false,
    scrollBeyondLastLine: false,
    readOnly: false,
    theme: "vs",
    fontSize: 24
  })

  // 设置监听事件
  codeEditor.onDidChangeModelContent(() => {
    emit('update:modelValue', codeEditor?.getValue())
  })
})
</script>

<template>
  <div ref="editorContainer" style="height: 100%; width: 100%"/>
</template>

<style scoped>

</style>

外部使用

vue 复制代码
<script setup lang="ts">
import CodeEditor from '@/components/editor/CodeEditor/CodeEditor.vue'
import { ref } from 'vue'

// 编程语言
const codeLanguage = ref('java')

// 代码编辑器值
const text = ref('')

</script>

<template>
  <a-row>
    <a-col :span="22" :offset="1">
      <md-edit style="border: 1px black solid" @getMdEditText="getMdEditText" />
      <div style="height: 500px; width: 100%; border: 1px black solid">
        <code-editor :language="codeLanguage" v-model="text"/>
        获取到的值:
        {{ text }}
      </div>
    </a-col>
  </a-row>
</template>

实现效果

v-model实现原理

v-model本身是vue提供的一个语法糖。v-model = @update:modelValue + :modelValue。

即当父组件中的modelValue值发生改变时,通过:modelValue传入子组件,子组件对完成页面渲染。当子组件中的钩子函数被触发时(即编辑器中的值被改变时),通过emit触发update:modelValue事件,向父组件中传值,父组件中修改modelValue的值。

相关推荐
紫金龙腾4 分钟前
EDGE 、chrome、浏览器显示“由你的组织管理”
前端·chrome·edge
用户66197734585758 分钟前
Vue3笔记
前端·vue.js
long31614 分钟前
适配器模式 java demo
java·javascript·后端·程序人生·设计模式·适配器模式
2401_837088501 小时前
ref 简单讲解
前端·javascript·vue.js
折果2 小时前
如何在vue项目中封装自己的全局message组件?一步教会你!
前端·面试
不死鸟.亚历山大.狼崽子2 小时前
Syntax Error: Error: PostCSS received undefined instead of CSS string
前端·css·postcss
汪子熙2 小时前
Vite 极速时代的构建范式
前端·javascript
叶常落2 小时前
[react] js容易混淆的两种导出方式2025-08-22
javascript
跟橙姐学代码2 小时前
一文读懂 Python 的 JSON 模块:从零到高手的进阶之路
前端·python
前端小巷子3 小时前
Vue3的渲染秘密:从同步批处理到异步微任务
前端·vue.js·面试