前端代码编辑组件

代码编辑组件界面

CodeEditor 组件基于 CodeMirror 封装,提供代码高亮、语法检查等编辑功能。

异步加载组件

组件采用异步加载方式,可按需引入,减少首屏加载体积。

const CodeEditor = defineAsyncComponent(
  () => import("/@/components/CodeEditor/index.vue")
);

使用方法

<template>
  <div>
    <CodeEditor
      v-model="code"
      mode="go"
      theme="idea"
      :readOnly="false"
      :height="300"
    />
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { defineAsyncComponent } from 'vue';

const CodeEditor = defineAsyncComponent(
  () => import("/@/components/CodeEditor/index.vue")
);

const code = ref('');
</script>

Props 属性

属性类型默认值说明
modelValueString''绑定的代码内容,支持 v-model 双向绑定
modeString'go'代码语言模式
themeString'idea'编辑器主题
heightString / Number300编辑器高度,数字自动添加 px,支持 '100%' 等
optionsObjectCodeMirror 配置选项,支持 showCopy 等
readOnlyBooleanfalse是否只读模式

支持的语言模式

语言支持

组件内置了以下语言模式的支持,通过 mode 属性指定:

mode 值语言类型
goGo 语言(默认)
shellShell 脚本
velocityVelocity 模板
text/x-javaJava
text/x-c++srcC++
text/x-csharpC#
<!-- Shell 脚本示例 -->
<CodeEditor v-model="shellCode" mode="shell" />

<!-- Java 代码示例 -->
<CodeEditor v-model="javaCode" mode="text/x-java" />

主题配置

组件内置两种主题风格:

主题说明
ideaIntelliJ IDEA 亮色风格(默认)
darculaDarcula 暗色风格
<!-- 使用暗色主题 -->
<CodeEditor v-model="code" theme="darcula" />
主题限制

组件仅内置了 idea 和 darcula 两种主题,如需使用其他主题需要额外引入对应的 CSS 文件。

复制按钮功能

通过 options 配置可以启用代码复制按钮,按钮悬浮在编辑器右上角:

<CodeEditor
  v-model="code"
  theme="darcula"
  :options="{ showCopy: true }"
/>
复制状态反馈

点击复制按钮后,图标会切换为勾选状态,2秒后自动恢复,提供良好的用户交互体验。

自定义配置

通过 options 属性可以传递 CodeMirror 的原生配置项:

<CodeEditor
  v-model="code"
  :options="{
    lineNumbers: true,
    lineWrapping: true,
    tabSize: 2,
    indentUnit: 2,
    showCopy: true
  }"
/>

常用配置项

配置项类型默认值说明
lineNumbersBooleantrue显示行号
lineWrappingBooleanfalse自动换行
tabSizeNumber4Tab 宽度
indentUnitNumber4缩进单位
indentWithTabsBooleantrue使用 Tab 缩进
styleActiveLineBooleantrue高亮当前行
showCopyBooleanfalse显示复制按钮
配置优先级

通过 options 传递的配置项优先级高于组件的 props 属性,可能会覆盖默认行为。