Created
June 27, 2022 01:58
-
-
Save composite/12522c83a7dfc95bf9f1a02e547af20f to your computer and use it in GitHub Desktop.
Monaco Editor for Vue example (SSR not works I don't know why...)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div ref="container"></div> | |
</template> | |
<script setup lang="ts"> | |
import {defineEmits, onBeforeUnmount, onMounted, ref, toRefs, watch} from 'vue'; | |
import {editor as editorType, IDisposable} from 'monaco-editor'; | |
import ICodeEditor = editorType.ICodeEditor; | |
export interface CodeEditorProps { | |
modelValue: string; | |
language: string; | |
} | |
const props = defineProps<CodeEditorProps>(); | |
const changeState = ref(false); | |
const { modelValue } = toRefs(props); | |
const emit = defineEmits<{ | |
(e: 'update:modelValue', value: string): void | |
}>(); | |
const container = ref<HTMLDivElement | null>(null); | |
const editor = ref<ICodeEditor | null>(null); | |
const subscriber = ref<IDisposable | null>(null); | |
watch(modelValue, (val) => { | |
if (editor.value) { | |
const edit = editor.value, model = edit.getModel(); | |
changeState.value = true; | |
edit.pushUndoStop(); | |
model.pushEditOperations([], [{ | |
range: model.getFullModelRange(), | |
text: val, | |
}], () => void 0); | |
edit.pushUndoStop(); | |
changeState.value = false; | |
} | |
}); | |
onMounted(() => { | |
if(container.value) { | |
import('monaco-editor').then(({ editor: monaco }) => { | |
editor.value = monaco.create(container.value, { | |
value: modelValue.value, | |
language: props.language, | |
}); | |
subscriber.value = editor.value.onDidChangeModelContent((e) => { | |
if (!changeState.value) { | |
const val = editor.value.getValue(); | |
if(modelValue.value !== val) emit('update:modelValue', val); | |
} | |
}); | |
}); | |
} | |
}); | |
onBeforeUnmount(() => { | |
editor.value?.dispose(); | |
subscriber.value?.dispose(); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment