Obtain the CodeMirror editor instance via events
mainYou can retrieve the CodeMirror Editor instance directly through the @ready and @change component events. This is often cleaner than using refs if you only need the instance when specific editor actions occur.
@ready: Emits theEditorinstance once the editor is initialized.@change: Emits the currentvalue(string) and theEditorinstance whenever the content changes.
<template>
<Codemirror
v-model:value="code"
:options="cmOptions"
@ready="onReady"
@change="onChange"
/>
</template>
<script lang="ts">
import { ref } from "vue";
import Codemirror from "codemirror-editor-vue3";
import type { Editor, EditorConfiguration } from "codemirror";
export default {
components: { Codemirror },
setup() {
const code = ref(`const ary = []`);
const cminstance = ref<Editor>();
const cmOptions: EditorConfiguration = {
mode: "javascript",
};
// The 'ready' event provides the Editor instance directly
const onReady = (cm: Editor) => {
cminstance.value = cm;
cminstance.value?.focus();
};
// The 'change' event provides the new value and the Editor instance
const onChange = (value: string, cm: Editor) => {
cminstance.value = cm;
cminstance.value?.focus();
};
return {
code,
cmOptions,
onReady,
onChange,
};
},
};
</script>