1、需求

 

       采用codemirror 6版本开发 ,要求:自定义代码提示通过输入关键字实现代码片段覆盖

        类似于Vscode中输入VueInit ,显示代码片段

<template lang="">
  <div>
    
  </div>
</template>
<script>
export default {
  
}
</script>
<style lang="">
  
</style>

         参考官网:CodeMirror Autocompletion Example 中的Providing Completions。

2、初始化

加载以下依赖

npm i codemirror
npm i @codemirror/autocomplete
npm i @codemirror/theme-one-dark

添加容器绑定id 

 <div id="codemir" ></div> 

js引用 


import { basicSetup, EditorView } from "codemirror";
import { oneDark } from "@codemirror/theme-one-dark"; //黑色主题编辑器
import { autocompletion } from "@codemirror/autocomplete"; 

在onMounted初始化codemirror  ,并添加对应id

const editor =   new EditorView({
      doc: "Press Ctrl-Space in here...n",
      extensions: [
        basicSetup, 
        oneDark, 
      ],
      parent: document.getElementById("coder"),
      options: {},
    });

3、设置代码提示

         其中from当前位置 , options自定义提示列表apply 需求中提到的自定义代码,还有info 信息提示 等。

function myCompletions(context) {
  let word = context.matchBefore(/w*/)
  if (word.from == word.to &amp;&amp; !context.explicit) return null;
  return {
    from: word.from,
    options: [
      { label: "match", type: "keyword" },
      { label: "hello", type: "variable", info: "(World)" },
      { label: "magic", type: "text", apply: "⠁⭒*.✩.*⭒⠁", detail: "macro" },
    ],
  };
} 

        最后,将codemirror绑定自定义的代码提示使用extensions

const editor =   new EditorView({
      doc: "Press Ctrl-Space in here...n",
      extensions: [
        basicSetup, 
        oneDark,
        autocompletion({ override: [myCompletions] })
      ],
      parent: document.getElementById("coder"),
      options: { 
      },
    });

4、其他优化 

        代码回显

editor.dispatch({
  changes: { from: 0, to: editor.state.doc.length, insert: content },
}); //插入content 

        以及代码更新监测

const editor =   new EditorView({
      doc: "Press Ctrl-Space in here...n",
      extensions: [
        basicSetup, 
        oneDark,
        autocompletion({ override: [myCompletions] }),
        EditorView.updateListener.of((v) => {
           console.log(v.state.doc.toString()) //监测得到的最新代码 
        }),
      ],
      parent: document.getElementById("coder"),
      options: { },
});

5、实现效果

原文地址:https://blog.csdn.net/qq_39078783/article/details/129883500

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_33614.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注