CodeMirror 5 + vue 实现插入标签功能,绑定id!

1,627 阅读1分钟

唉~,为啥要用CodeMirror5 呢? 因为调研的时候,没看到项目里已经使用了CodeMirror5.....,说多了都是泪

效果

直接上代码

html

  <div ref="editor" class="editor"></div>

js

insert(row) {            //获取codemirror光标位置      const pos1 = this.editor.getCursor()      const pos2 = {}      pos2.line = pos1.line      pos2.ch = pos1.ch      //制作标签dom(颜色样式自行设置)      const dom = document.createElement('span')      dom.className = 'cm-field'      dom.textContent = row.name

      // 方便标记 字段id      const bookMark = `[[${row.id}.${row.name}]]`      const endPos = { line: pos2.line, ch: pos2.ch + 2 + bookMark.length }      //先插入字符串      this.editor.replaceRange(bookMark, pos2)      // 再对插入字符串进行标签制定(其实就是在codemirror中动态添加标签)      this.editor.markText(pos2, endPos, {        replacedWith: dom,        atomic: true,        className: 'cm-field2',        handleMouseEvents: true      })      console.log(this.editor.getValue()) //获取codemirror内容      setTimeout(() => {        this.editor.focus()      }, 0)    },

注意!!! 写完这些后,很多同学都会遇到这种错误,点击编辑器报错、按键报错、光标显示错乱等。。。

这个是因为vue对象有代理,而codeMirror调用成员函数必须是从原始对象调用

所以,

我们需要在初始化的时候markRaw()一下,即

formula.value = markRaw(      new CodeMirror(editor.value, {        lineNumbers: true,        mode: 'javascript',        gutters: ['CodeMirror-lint-markers'],        lint: true,        line: true,        tabSize: 2,        lineNumbers: false,        lineWrapping: true,        value: val || '',        readOnly: false      })    )