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的值。

相关推荐
跳动的梦想家h23 分钟前
环境配置 + AI 提效双管齐下
java·vue.js·spring
夏幻灵43 分钟前
HTML5里最常用的十大标签
前端·html·html5
冰暮流星44 分钟前
javascript之二重循环练习
开发语言·javascript·数据库
Mr Xu_1 小时前
Vue 3 中 watch 的使用详解:监听响应式数据变化的利器
前端·javascript·vue.js
未来龙皇小蓝1 小时前
RBAC前端架构-01:项目初始化
前端·架构
程序员agions1 小时前
2026年,微前端终于“死“了
前端·状态模式
万岳科技系统开发1 小时前
食堂采购系统源码库存扣减算法与并发控制实现详解
java·前端·数据库·算法
程序员猫哥_1 小时前
HTML 生成网页工具推荐:从手写代码到 AI 自动生成网页的进化路径
前端·人工智能·html
龙飞051 小时前
Systemd -systemctl - journalctl 速查表:服务管理 + 日志排障
linux·运维·前端·chrome·systemctl·journalctl
我爱加班、、1 小时前
Websocket能携带token过去后端吗
前端·后端·websocket