Skip to content

Instantly share code, notes, and snippets.

@composite
Created June 27, 2022 01:58
Show Gist options
  • Save composite/12522c83a7dfc95bf9f1a02e547af20f to your computer and use it in GitHub Desktop.
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...)
<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