vue-codemirror6

logueMIT活跃维护

把 CodeMirror 6 封装成 Vue 组件,Vue2 和 Vue3 都能直接用,省去手动绑定编辑器实例和响应式状态的麻烦。

⌨️ @codemirror 6 component for @vuejs. Vue2 & Vue3 both supported.

1.4.0发布于 2025-10-17 01:43 UTC207star23fork同步于 2026-11-07 07:32 UTC

怎么上手

由 README 提炼,执行前请确认
pnpm install vue-codemirror6 codemirror
硬件要求按 README 说明

README 未说明

下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

把 CodeMirror 6 封装成 Vue 组件的库,Vue2 和 Vue3 都能直接用

把 CodeMirror 6 封装成 Vue 组件,Vue2 和 Vue3 都能直接用,省去手动绑定编辑器实例和响应式状态的麻烦。

核心能力

  • 用 v-model 实现双向绑定,像普通 Vue 组件一样使用
  • 支持 basicSetup 和 minimalSetup 两种预设配置
  • 通过 lang 属性接入官方语言包实现语法高亮
  • 通过 linter 和 gutter 属性显示错误标记
  • 支持自定义主题、快捷键和扩展插件

容易踩的坑

Vue 2.7 及以下版本需要额外安装 @vue/composition-api;语法高亮需要自行安装对应的 @codemirror/lang-* 语言包;linter 和 gutter 需要配合 linter 属性使用,否则不生效

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

3 个版本1.4.0
  1. 1.4.0最新正式版2025-10-17 · 2025-10-17 01:43 UTC

    Add SSR support.

    What's Changed

    New Contributors

    Full Changelog: https://github.com/logue/vue-codemirror6/compare/1.3.13...1.4.0

  2. 1.1.122023-03-10 · 2023-03-10 15:37 UTC
    查看更新说明

    What's Changed

    New Contributors

    Full Changelog: https://github.com/logue/vue-codemirror6/compare/1.1.11...1.1.12

  3. 1.1.02022-10-31 · 2022-10-31 13:59 UTC
    查看更新说明

    See CHANGELOG.md

    BREAKING CHANGS

    • editable prop become to disabled (inverse value).
    • lint-gutter prop become gutter.
    • changed emit become change.

    Full Changelog: https://github.com/logue/vue-codemirror6/compare/1.0.3...1.1.0

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    vue-codemirror6

    English | 日本語

    npm version NPM Downloads jsdelivr CDN Open in unpkg Open in Gitpod X Follow GitHub Sponsors

    A component for using CodeMirror6 with Vue. This component works in both Vue2 and Vue3.

    Usage

    pnpm install vue-codemirror6 codemirror
    

    For Vue 2.7 or below, @vue/composition-api is required separately.

    pnpm install vue-codemirror6 @vue/composition-api
    

    This component can handle bidirectional binding by v-model like a general Vue component.

    Props

    PropsTypeInformation
    model-valuestring | TextText value. (Not value)
    basicbooleanUse basicSetup.
    minimalbooleanUse miniSetup. If a basic prop is also specified, that setting will take precedence.
    darkbooleanToggle Darkmode.
    placeholderstringAdd placeholder text (or HTML DOM) when blank
    wrapbooleanLine text wrapping. see lineWrapping.
    tabbooleanEnables tab indentation.
    allow-multiple-selectionsbooleanAllow Multiple Selection. See allowMultipleSelections
    tab-sizenumberConfigures the tab size to use in this state.
    line-separatorstringSet line break (separetor) char. (Default is \n.)
    theme{ [selector: string]: StyleSpec }Specify the theme. For example, if you use @codemirror/theme-one-dark, import oneDark and put it in this prop.
    readonlybooleanMakes the cursor visible or you can drag the text but not edit the value.
    disabledbooleanThis is the reversed value of the CodeMirror editable. Similar to readonly, but setting this value to true disables dragging.
    langLanguageSupportThe language you want to have syntax highlighting. see https://codemirror.net/6/#languages
    phrasesRecord<string, string>Specify here if you want to make the displayed character string multilingual. see https://codemirror.net/6/examples/translate/
    extensionsExtension[]Includes enhancements to extend CodeMirror.
    linterLintSourceSet Linter. Enter a linter (eg esLint([arbitrary rule]) function for @codemirror/lang-javascript, jsonParseLinter()function for@codemirror/json). See the sources for various language libraries for more information.
    linterConfigObjectsee https://codemirror.net/docs/ref/#lint.linter^config
    forceLintingbooleansee https://codemirror.net/docs/ref/#lint.forceLinting
    gutterbooleanDisplay 🔴 on the line where there was an error when linter was specified. It will not work if linter is not specified.
    gutterConfigObjectsee https://codemirror.net/docs/ref/#lint.lintGutter^config
    tagstringHTML tags used in the component. (Default is div tag.)
    scrollIntoViewbooleanAllows an external update to scroll the form. (Default is true)
    preserveScrollPositionbooleanPreserves the editor scroll position when modelValue is updated externally. Useful to prevent jumping to the top during appended updates. (Default is false)
    keymapKeyBinding[]Key bindings associate key names with command-style functions. See https://codemirror.net/docs/ref/#view.KeyBinding

    ⚠ Notice: lang and linter can also be set together in extensions. These are separated for compatibility with previous versions of CodeMirror settings and for typing props.

    Supported Languages

    Official

    Unofficial

    Supported Themes

    Example

    Mark up as follows to make it work at a minimum.

    <template>
      <code-mirror v-model="value" />
    </template>
    
    <script>
    import { ref, defineComponent } from "vue";
    
    import CodeMirror from "vue-codemirror6";
    
    export default defineComponent({
      components: {
        CodeMirror,
      },
      setup() {
        const value = ref("Cozy lummox gives smart squid who asks for job pen.");
    
        return { value };
      },
    });
    </script>
    

    Example using Slots

    The contents of the slot will overwrite the existing v-model. For this reason, it is recommended to use it when simply displaying with a readonly prop without using v-model.

    Also, insert a <pre> tag to prevent the text in the slot from being automatically formatted.

    <template>
      <code-mirror :lang="lang" :linter="linter">
        <pre>
    {
      "key": "value"
    }</pre
        >
      </code-mirror>
    </template>
    
    <script>
    import { ref, defineComponent } from "vue";
    
    import { json, jsonParseLinter } from "@codemirror/lang-json";
    
    import CodeMirror from "vue-codemirror6";
    
    export default defineComponent({
      components: {
        CodeMirror,
      },
      setup() {
        const lang = json();
        const linter = jsonParseLinter();
        return { lang, linter };
      },
    });
    </script>
    

    Using with SSR (Nuxt.js, etc.)

    This component is now SSR-compatible. CodeMirror will only be initialized on the client side, and the component will safely render without errors during server-side rendering.

    If you're using Nuxt 3, you can use the component directly:

    <template>
      <code-mirror v-model="value" :lang="lang" />
    </template>
    
    <script lang="ts" setup vapor>
    import { ref } from "vue";
    import CodeMirror from "vue-codemirror6";
    import { javascript } from "@codemirror/lang-javascript";
    
    const value = ref('console.log("Hello, World!");');
    const lang = javascript();
    </script>
    

    For Nuxt 2 or if you encounter any issues, you can wrap the component with <ClientOnly>:

    <template>
      <client-only>
        <code-mirror v-model="value" :lang="lang" />
      </client-only>
    </template>
    

    Full Example

    When using as a Markdown editor on vite-vue3-ts-starter.

    <script lang="ts" setup vapor>
    import { ref, defineComponent, type Ref } from "vue";
    
    // Load component
    import CodeMirror from "vue-codemirror6";
    
    // CodeMirror extensions
    import { markdown as md } from "@codemirror/lang-markdown";
    import type { LanguageSupport } from "@codemirror/language";
    import type { Extension } from "@codemirror/state";
    import type { ViewUpdate } from "@codemirror/view";
    
    /** text */
    const value: Ref<string> = ref("");
    
    /** Dark mode **/
    const dark: Ref<boolean> = ref(
      window.matchMedia("(prefers-color-scheme: dark)").matches,
    );
    
    /**
     * CodeMirror Language
     *
     * @see {@link https://codemirror.net/6/docs/ref/#language | @codemirror/language}
     */
    const lang: LanguageSupport = md();
    
    /**
     * Internationalization Config.
     * In this example, the display language to Japanese.
     * Must be reactive when used in combination with vue-i18n.
     *
     * @see {@link https://codemirror.net/6/examples/translate/ | Example: Internationalization}
     */
    const phrases: Record<string, string> = {
      // @codemirror/view
      "Control character": "制御文字",
      // @codemirror/commands
      "Selection deleted": "選択を削除",
      // @codemirror/language
      "Folded lines": "折り畳まれた行",
      "Unfolded lines": "折り畳める行",
      to: "行き先",
      "folded code": "折り畳まれたコード",
      unfold: "折り畳みを解除",
      "Fold line": "行を折り畳む",
      "Unfold line": "行の折り畳む解除",
      // @codemirror/search
      "Go to line": "行き先の行",
      go: "OK",
      Find: "検索",
      Replace: "置き換え",
      next: "▼",
      previous: "▲",
      all: "すべて",
      "match case": "一致条件",
      "by word": "全文検索",
      regexp: "正規表現",
      replace: "置き換え",
      "replace all": "すべてを置き換え",
      close: "閉じる",
      "current match": "現在の一致",
      "replaced $ matches": "$ 件の一致を置き換え",
      "replaced match on line $": "$ 行の一致を置き換え",
      "on line": "した行",
      // @codemirror/autocomplete
      Completions: "自動補完",
      // @codemirror/lint
      Diagnostics: "エラー",
      "No diagnostics": "エラーなし",
    };
    </script>
    
    <template>
      <code-mirror
        v-model="value"
        basic
        :dark="dark"
        :lang="lang"
        :phrases="phrases"
      />
    </template>
    

    Events

    EventDescription
    readyWhen CodeMirror loaded.
    focusWhen focus changed.
    updateWhen CodeMirror state changed. Returns ViewUpdate object.
    changeValue changed. Returns EditorState

    Parameter / Function

    <script lang="ts" setup vapor>
    import { ref, onMounted, type Ref, type PropType } from "vue";
    import CodeMirror from "vue-codemirror6";
    
    const cm: Ref<InstanceType<typeof CodeMirror> | undefined> = ref();
    
    onMounted(() => {
      console.log(cm.value?.json);
    });
    </script>
    <template>
      <code-mirror ref="cm" />
    </template>
    
    Function / ParameterDescription
    viewGet and set EditorView.
    selectionGet and set the EditorSelection instance.
    cursorGet and set the cursor location.
    jsonGet and set state to a JSON-serializable object.
    focusGet and set focus.
    lint()Force run linter (Only if linter prop is specified)
    forceReconfigure()Re register all extensions.

    CodeMirror5 backward compatible functions

    The instructions below are compatible methods for those familiar with codemirror5. Since the above method is usually sufficient, its active use is not recommended.

    FunctionDescription
    getRange(from?: number, to?: number)Get the text between the given points in the editor.
    getLine(number: number)Get the content of line.
    lineCount()Get the number of lines in the editor.
    getCursor()Retrieve one end of the primary selection.
    listSelections()Retrieves a list of all current selections.
    getSelection()Get the currently selected code.
    getSelections()The length of the given array should be the same as the number of active selections.
    somethingSelected()Return true if any text is selected.
    replaceRange(replacement: string | Text, from: number, to: number)Replace the part of the document between from and to with the given string.
    replaceSelection(replacement: string | Text)Replace the selection(s) with the given string.
    setCursor(position: number)Set the cursor position.
    setSelection(anchor: number, head?: number)Set a single selection range.
    setSelections(ranges: readonly SelectionRange[], primary?: number)Sets a new set of selections.
    extendSelectionsBy(f: Function)Applies the given function to all existing selections, and calls extendSelections on the result.

    WebComponents Feature (Experimental)

    By importing it with CodeMirror, it can also be used as a Web Component.

    import { CodeMirror } from "vue-codemirror6";
    
    customElements.define("code-mirror", CodeMirror);
    
    <code-mirror></code-mirror>
    

    Recommendations

    Since CodeMirror has a relatively large capacity, when using vite, it is recommended to set it to output as a separate file using the manualChunks option at build time as shown below.

    const config: UserConfig = {
      // ...
      build: {
        rollupOptions: {
          output: {
            manualChunks: {
              // ...
              codemirror: ["vue-codemirror6"],
              "codemirror-lang": [
                // Add the following as needed.
                "@codemirror/lang-html",
                "@codemirror/lang-javascript",
                "@codemirror/lang-markdown",
              ],
              // ...
            },
          },
        },
      },
      // ...
    };
    

    Development

    Testing

    This project uses Vitest for unit testing.

    # Run tests
    pnpm test
    
    # Run tests in watch mode
    pnpm test:watch
    
    # Run tests with UI
    pnpm test:ui
    
    # Run tests with coverage
    pnpm test:coverage
    

    The test suite includes:

    • Component Tests: Testing basic rendering, props, events, and v-model binding
    • SSR Tests: Ensuring proper server-side rendering compatibility for Nuxt.js and other SSR frameworks
    • Method Tests: Verifying all exposed methods work correctly
    • Edge Cases: Testing error handling and unusual scenarios

    LICENSE

    ©2022-2026 by Logue. Licensed under the MIT License.