vue3中使用codemirror6增加代码提示功能

1、安装依赖

// 安装codemirror、语言包、主题、自动补全

npm i codemirror

npm i @codemirror/lang-javascript

npm i @codemirror/auto***plete

npm i @codemirror/theme-one-dark

本人安装的版本是

"dependencies": {
    "@codemirror/auto***plete": "^6.0.0",
    "@codemirror/lang-javascript": "^6.0.2",
    "@codemirror/theme-one-dark": "^6.0.0",
    "codemirror": "^6.0.1",
    ...
},

2、创建编辑器

<template>
  <el-select
    placeholder="请选择分组"
    v-model="group"
    clearable
    @change="insertGroup"
  >
    <el-option
      v-for="dict in groupList
      :key="dict.id"
      :label="dict.dgName + '(' + dict.dgCode + ')'"
      :value="dict.dgCode"
    ></el-option>
  </el-select>
  <el-button @click="codeBeauty" style="margin-bottom: 0.5rem">代码格式化</el-button>
  <div id="coder"></div>
  <el-button type="primary" @click="submitForm" v-if="!testFlag">确 定</el-button>
</template>
<style scoped>
#coder{
  margin-top: 10px;
  width: 100%;
}
</style>
<script setup name="***mand">
import { javascript } from "@codemirror/lang-javascript";
import { oneDark } from "@codemirror/theme-one-dark";
import { basicSetup, EditorView } from "codemirror";
import { auto***pletion } from "@codemirror/auto***plete"; 

const { proxy } = getCurrentInstance();
const allKeyList = ref([]);
const groupList = ref([]);
const group = ref("");
const data = reactive({
  form: {},
});
const { form } = toRefs(data);

let editor = null;

// 获取自定义提示内容
function get***mandList() {
    groupList.value = [
        { id: '1', label: '分组1', value: 'group1' },
        { id: '2', label: '分组2', value: 'group2' },
    ]; 
    allKeyList.value = [
      { label: "@match", type: "keyword", apply: "match", detail: "match" },
      { label: "@hello", type: "variable", apply: "hello", detail: "hellodetail" },
      { label: "@magic", type: "text", apply: "⠁⭒*.✩.*⭒⠁", detail: "macro" },
    ];
}

// 代码美化
function codeBeauty() {
  editor.dispatch({
    changes: { 
        from: 0, 
        to: editor.state.doc.length, 
        insert:js_beautify(get***manContent() || "") 
    },
  });
}
// 获取当前编辑器中的内容字符串
function get***manContent() {
  let str = ""
  editor.state.doc.children.forEach((el,index) => {
    str += el.text.join("\n") + "\n"
  })
  return str.slice(0,-1);
}
// 初始化编辑器
function initCodeContent(){
  setTimeout(() => {
    if(!editor) {
      editor = new EditorView({
        doc: "Press Ctrl-Space in here...\n",
        extensions: [
          basicSetup,
          javascript(),
          oneDark,
          auto***pletion({ override: [my***pletions] }),
          // EditorView.updateListener.of((v) => {
          //   console.log(v.state.doc.toString()) 
          // }),
        ],
        parent: document.getElementById("coder"),
        options: {
          lineNumbers: true,
          line: true,
          //ctrl-space唤起智能提示
          extraKeys: {
            Ctrl: "auto***plete",
          },
          //括号匹配
          matchBrackets: true,
        },
      });
    }
    editor.dispatch({
      changes: { 
        from: 0, 
        to: editor.state.doc.length, 
        insert: form.value.***mandContent || "Press Ctrl-Space in here...\n" 
      },
    });
  }, 500);
}

// 自定义的代码不全,options为自定义内容,以@开头进行匹配
function my***pletions(context) {
  let word = context.matchBefore(/@\w*/);
  if (!word && !context.explicit) return null;
  return {
    from: word.from ? word.from : context.pos,
    options: allKeyList.value,
  };
}

// 选择分组添加到编辑其中
function insertGroup() {
  insert***mandContant(group.value);
  group.value = "";
}

// 外部输入内容,添加到编辑器当前光标(或选中内容)所在的位置
function insert***mandContant(insertContent) {
  editor.dispatch({
    changes: { 
        from: editor.state.selection.ranges[0].from, 
        to: editor.state.selection.ranges[0].to, 
        insert: insertContent 
    },
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$modal.loading("正在保存,请稍候...");
  form.value.***mandContent = get***manContent();
  addForm(form.value).then((response) => {
    proxy.$modal.msgSu***ess("新增成功");
    proxy.$modal.closeLoading();
  }).catch((err) => {proxy.$modal.closeLoading();});
}


get***mandList();
initCodeContent();

</script>

转载请说明出处内容投诉
CSS教程_站长资源网 » vue3中使用codemirror6增加代码提示功能

发表评论

欢迎 访客 发表评论

一个令你着迷的主题!

查看演示 官网购买