// codemirror引用
  <codemirror
          ref="mycode"
          :options="cmOptions"
          @changes="changeContent"
          class="codemirror-area"
        ></codemirror>
        
import { codemirror } from "vue-codemirror";
import "codemirror/lib/codemirror.css";

import "codemirror/theme/base16-light.css"; // 这里引入的是主题样式
import "codemirror/mode/javascript/javascript.js"; // 这里引入的模式的js

export default {
components: { codemirror },
  data() {
    return {
      content :''
      cmOptions: {
        lineWrapping: true,
        tabSize: 4, // Tab键空格数
        mode: "text/javascript", // 模式
        theme: "base16-light", // 主题
        line: true,
        // autofocus: true,//首次载入自动聚焦
      },
    };
  }
  methods:{
	  insert(row) {
	  	  //获取codemirror光标位置
	  	  const pos1 = this.$refs.mycode.codemirror.getCursor()
	      const pos2 = {};
	      pos2.line = pos1.line;
	      pos2.ch = pos1.ch;
	      
	      //制作标签dom(颜色样式自行设置)
	      var dom = document.createElement("span");
	      dom.className = "cm-field";
	      dom.innerHTML = row.name;
	      
	      const bookMark = row.name;
	      const endPos = { line: pos2.line, ch: pos2.ch + bookMark.length };
	      
	      this.$refs.mycode.codemirror.replaceRange(bookMark, pos2);//先插入字符串
	      
	      //再对插入字符串进行标签制定(其实就是在codemirror中动态添加标签)
	      this.$refs.mycode.codemirror.markText(pos2, endPos, {
	        replacedWith: dom,
	      });
	      this.content = this.$refs.mycode.codemirror.getValue();//获取codemirror内容
	      }
	  }
}
<style lang="scss" scoped>
::v-deep {
  .cm-field {
    background-image: linear-gradient(-117deg, #90dcd4, #7cdfc2);
  }
  .cm-current-field,
  .cm-field {
    display: inline-block;
    height: 22px;
    line-height: 22px;
    color: #fff;
    margin: 0 3px;
    border-radius: 3px;
    padding: 0 8px;
    font-size: 13px;
  }
  .cm-delField {
    display: inline-block;
    height: 22px;
    line-height: 22px;
    background: #f26245;
    color: #fff;
    margin: 0 3px;
    border-radius: 3px;
    padding: 0 8px;
    font-size: 13px;
  }
  .CodeMirror-widget {
    height: 28px;
    line-height: 28px;
  }
}

在这里插入图片描述
大致显示内容截图,
笔者只是初步理解codemirror操作,具体细节可能还未能考虑周到,如有建议欢迎留言~

Logo

前往低代码交流专区

更多推荐