Using codemirror in vue3

foreword

Recently, in order to complete the big homework in school, it is necessary to make a markdown editor. For the convenience of user input, codemirror is used as the editor. This article introduces only a very simple configuration. For more information, please refer to the official documentation .

introduce

npm i codemirror

Use in vue3

basic configuration

For specific configuration, please refer to the official website
https://codemirror.net/5/doc/manual.html#config

// html部分
<textarea ref="l"></textarea>

// 引入
import CodeMirror from "codemirror";

// codemirror配置
const l = ref(null);
onMounted(() => {
    
    
     const editor=CodeMirror.fromTextArea(l.value, {
    
    
       mode: "markdown",// 模式
       theme: "solarized", // 主题
       lineWrapping: true,// 自动换行
       scrollPastEnd: true,// 允许用户将一个编辑器高度的空白区域滚动到编辑器底部的视图
       lineNumbers: true,// 显示左边行号(默认false,即不显示)
       styleActiveLine: true, // 当前行背景高亮
     });
}

Change the outer style (height, width) of the edit box

The first way to change css

.CodeMirror {
    
    
  border: 1px solid #eee;
  height: auto;
}

The second uses the editor.setSize() method, the first is wide and the second is high

Get and modify content

// 获取
editor.getValue();
// 修改
editor.setValue('要赋予的值');

add delete event

For details, please refer to the official website
https://codemirror.net/5/doc/manual.html#events
to change (triggered when the content of the editor changes, similar to the change of input) as an example:

editor.on('change', (cm, msg) => {
    
    
        console.log(cm == editor);// true
        console.log(msg);// 改变内容的信息
})

Screenshot of the second parameterinsert image description here

Bugs encountered in the process of implementing markdown

  1. You can scroll without content, the height value of the original .CodeMirror-sizer is 120% (I have been looking for it for a long time/(ㄒoㄒ)/~~
.CodeMirror-sizer {
    
    
        height: 100%;
      }
  1. In the process of realizing synchronous scrolling, the mouse does not scroll, but the page still scrolls, because scrolling events are bound on both sides, forming an endless loop. Workaround: Set a variable to record which side is currently triggering scrolling.
    insert image description here
  2. codemirror报错 Uncaught TypeError: Cannot read properties of undefined (reading ‘map‘)

Reason: Since I used pinia to store the codemirror object, the codemirror object became a proxy object when it was acquired and used, and the real codemirror object was not used.
Solution: Use toRaw() to get the real codemirror object before using it.

import {
    
     toRaw } from "@vue/reactivity";
const editor = toRaw(editorStore().editor);

In this way, if you use it again, you will not report an error.
I don't know the reason why this error occurs at present, if anyone knows, please let me know, thank you! ! !

Guess you like

Origin blog.csdn.net/m0_53062835/article/details/127642057