VUE3 插件 vue-codemirror 使用步骤和实例、基于 CodeMirror ,适用于 Vue 的 Web 代码编辑器。
第一步:安装 vue-codemirror & codemirror 包 , 以及语言包
npm install codemirror --save
npm install vue-codemirror --save
npm install @codemirror/lang-javascript --save
npm install @codemirror/lang-python --save
npm install @codemirror/lang-cpp --save
npm install @codemirror/theme-one-dark --save
第二步:在需要的组件中配置
src\components\code\Index.vue
<script setup>
import {
watch, ref, toRefs , computed
} from 'vue';
import { Codemirror } from 'vue-codemirror';
import { javascript } from '@codemirror/lang-javascript';
import { python } from '@codemirror/lang-python';
import { oneDark } from '@codemirror/theme-one-dark';
const code = ref('');
const props = defineProps({
modelValue: {
type: String,
required: false,
default: ''
},
language: {
type: String,
default: 'javascript'
},
disabled: {
type: [String, Boolean],
default: false
},
style: {
type: [Object],
default: () => ({
height: '400px'
})
}
})
const emit = defineEmits(['update:modelValue'])
const {modelValue, language, disabled, style } = toRefs(props)
const fullScreen = ref(false);
const lang = { javascript, python }[language.value];
const extensions = [lang(), oneDark]
watch(() => modelValue.value, (val) => {
code.value = val;
});
watch(code.value, (val) => {
emit('update:modelValue', val);
});
const comStyle = computed(() => ({ ...style.value, ...{ height: fullScreen.value ? '100%' : '400px' } }));
</script>
<template>
<Codemirror
:disabled="disabled"
v-model="code"
placeholder="暂无数据..."
:style="comStyle"
:autofocus="true"
:indent-with-tab="true"
:tabSize="2"
:fullScreen="true"
:extensions="extensions"
@ready="() => {}"
@change="() => {}"
@focus="() => {}"
@blur="() => {}"
></Codemirror>
</template>
第三步:使用
<script setup lang="ts">
import { ref } from 'vue'
import Code from '@common/code/Index.vue'
const fetchTxtFileData = ref('你好 世界!')
</script>
<template>
<Code v-model="fetchTxtFileData" :style="{width: '47vw'}"></Code>
</template>