文章目录
- 背景
- 环境说明
- 安装流程以及组件封装
- 引入依赖
- 封装组件
- 外部使用
- 实现效果
- v-model实现原理
背景
做oj系统的时候,需要使用代码编辑器,决定使用Monaco Editor,但是因为自身能力问题,读不懂官网文档,最终结合ai和网友的帖子成功引入,并封装了组件,支持v-model接收文档内容。希望可以帮助到别人。
环境说明
- vite
- vue3
- pnpm
安装流程以及组件封装
引入依赖
pnpm install monaco-editor
封装组件
<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>
外部使用
<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的值。