官方文档:https://github.com/RennCheung/codemirror-editor-vue3
国内镜像:https://renncheung.github.io/codemirror-editor-vue3/zh-CN/guide/getting-started
1.安装
npm install codemirror-editor-vue3 codemirror@5.x -S
2.代码示例
<template><Codemirrorv-model:value="code":options="cmOptions"borderref="cmRef"height="400"width="600"@change="onChange"@input="onInput"@ready="onReady"></Codemirror>
</template>
<script>import { ref, onMounted, onUnmounted } from "vue"import "codemirror/mode/javascript/javascript.js"import Codemirror from "codemirror-editor-vue3"export default {components: { Codemirror },setup() {const code = ref(`var i = 0;
for (; i < 9; i++) {console.log(i);// more statements
}
`)const cmRef = ref()const cmOptions = {mode: "text/javascript"}const onChange = (val, cm) => {console.log(val)console.log(cm.getValue())}const onInput = (val) => {console.log(val)}const onReady = (cm) => {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()})return {code,cmRef,cmOptions,onChange,onInput,onReady}}}
</script>
3.支持多种语言
参考文档:https://codemirror.net/5/mode/index.html
- 点击参考文档,选择语言并点击在文章最后找到mode的格式
- 在配置项中修改mode,并引入对应语言js
如使用python
在参考文档中找到MIME types defined: text/x-python and text/x-cython.
引入并使用python语言,一定要引入对应js才能使用
import "codemirror/mode/python/python.js"
const cmOptions = {mode: "text/x-python", // Use the Python mode
}