1 安装
pnpm i codemirror-editor-vue3 codemirror@^5 -S
2 TS支持
pnpm i @types/codemirror -D
3.示例(按TAB补全代码)
<template>
<Codemirror v-model:value="code" :options="cmOptions" border ref="cmRef" height="400" width="600"
@change="onChange" @input="onInput" @ready="onReady">
</Codemirror>
</template>
<script setup>
import "codemirror/mode/sql/sql.js";
import Codemirror from "codemirror-editor-vue3";
import type { CmComponentRef } from "codemirror-editor-vue3";
import type { Editor, EditorConfiguration } from "codemirror";
// 引入代码自动提示插件
import 'codemirror/addon/hint/show-hint.css';
import 'codemirror/addon/hint/sql-hint';
import 'codemirror/addon/hint/show-hint';
const code = ref(
``
);
const cmRef = ref<CmComponentRef>();
const cmOptions: EditorConfiguration = {
mode: "sql",
extraKeys: { // 触发按键
'Ctrl': 'autocomplete'
},
hintOptions: { // 自定义提示选项
completeSingle: false, // 当匹配只有一项的时候是否自动补全
tables: {
users: ['name', 'score', 'birthDate'],
countries: ['name', 'population', 'size'],
score: ['zooao'],
}
}
};
const onChange = (val: string, cm: Editor) => {
console.log(cm.getValue());
};
const onInput = (val: string) => {
cmRef.value?.cminstance.showHint();
};
const onReady = (cm: Editor) => {
console.log(cm.focus());
};
onMounted(() => {
setTimeout(() => {
cmRef.value?.refresh();
}, 1000);
setTimeout(() => {
cmRef.value?.resize(300, 200);
}, 2000);
setTimeout(() => {
cmRef.value?.cminstance.isClean();
}, 3000);
});
onUnmounted(() => {
cmRef.value?.destroy();
});
</script>