文章目錄
- 背景
- 環境說明
- 安裝流程以及組件封裝
- 引入依賴
- 封裝組件
- 外部使用
- 實現效果
- 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的值。