Skip to content

组件事件

以下三种仅是本组件封装的事件,更多事件请查阅 Codemirror Events

事件名称说明参数
change或者实例改变(value: string, cm: Editor) => void
inputinput(value: string) => void
ready组件加载完成(cm: Editor) => void;

示例:

vue
<template>
  <Codemirror
    v-model:value="code"
    :options="cmOptions"
    border
    @change="onChange"// [!code focus]
    @input="onInput"// [!code focus]
    @ready="onReady"// [!code focus]
  >
  </Codemirror>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import "codemirror/mode/javascript/javascript.js";
import Codemirror from "codemirror-editor-vue3";
import type { Editor, EditorConfiguration } from "codemirror";

const code = ref('console.log("name")');

const cmOptions: EditorConfiguration = {
  mode: "text/javascript",
  lint: true,
};

const onChange = (val: string, cm: Editor) => {
  console.log(val);
  console.log(cm.getValue());
};

const onInput = (val: string) => {
  console.log(val);
};

const onReady = (cm: Editor) => {
  console.log(cm.focus());
};
</script>

注意 merge(diff) 模式下 change 事件有所不同, 示例:

Details
vue
<template>
  <Codemirror
    v-model:value="code"
    :options="cmOptions"
    border
    @change="onChange"// [!code focus]
  >
  </Codemirror>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import "codemirror/mode/javascript/javascript.js";
import Codemirror from "codemirror-editor-vue3";
import type { Editor, EditorConfiguration } from "codemirror";
import type { MergeView } from "codemirror/addon/merge/merge";

const code = ref('console.log("name")');

const cmOptions: EditorConfiguration = {
  mode: "text/javascript",
  lint: true,
};

const onChange = (val: string, cm: any) => {      
  console.log(val);
  const cmMerge = cm as MergeView;
  const cminstance: Editor = cmMerge.editor();
  console.log(cminstance.getValue());
};

</script>

Codemirror 自身事件

TIP

以下事件为 Codemirror5 官方自身事件,具体内容可以查阅官方文档 Codemirror Event,使用本插件时可以直接通过组件绑定事件,例如:

vue
<Codemirror
  v-model:value="code"
  :options="{ mode: 'text/x-vue', theme: 'default' }"
  border
  placeholder="test-placeholder"
  :height="200"
  @change="onChange"
  @blur="onBlur"
  @focus="onFocus"
  @scroll="onScroll"
/>

所有事件名称如下:

  • changes
  • scroll
  • beforeChange
  • cursorActivity
  • keyHandled
  • inputRead
  • electricInput
  • beforeSelectionChange
  • viewportChange
  • swapDoc
  • gutterClick
  • gutterContextMenu
  • focus
  • blur
  • refresh
  • optionChange
  • scrollCursorIntoView
  • update

Released under the MIT License.