vue中codemirror自定义自动补全

一、下载并引入vue-codemirror

1、下载

npm install vue-codemirror

2、引入

   <codemirror
        ref="editor"
        class="code"
        v-model="data"
        :options="mirrorOptions"
        @focus="focusHandle"
        @blur="blurHandle"
        @changes="changeHandle"
        @ready="readyHandle"
    ></codemirror>

import { codemirror } from 'vue-codemirror';
import CodeMirror from "codemirror";
//引入提示样式文件
require('codemirror/addon/hint/show-hint.css');
require('codemirror/addon/hint/show-hint.js');
require('codemirror/addon/hint/sql-hint.js');
require('codemirror/addon/hint/javascript-hint.js');

二、在ready事件中定义自动提示方法

private readyHandle(codemirror:CodeEditor) {
        	this.codemirror = codemirror;
            
          	this.codeEditor.on("keypress", () => {
                //编译器内容更改事件
                const config = {
                    // 自定义提示选项
                    completeSingle: false, // 当匹配只有一项的时候是否自动补全
                    hint: hint,
                };
                this.codeEditor?.showHint(config);
            });

		  const hint = (editor: CodeEditor, callback: (str: Record<string, unknown>) => void) => {
		  	//获取CodeMirror上面的一个方法
            const Pos = CodeMirror.Pos;
            // 获取光标位置
            const cur = editor.getCursor();
            // 获取当前单词的信息
            const token = editor.getTokenAt(cur as unknown as { string: string; start: number; end: number });
            //用来放提示的单词
            let found: string[] = [];
            //当前正在输入的单词 通过它判断提示啥啥
            const currentStr = token.string;
            //一个简单的示例 输入if后提示数组中的
            if (currentStr === "if") {
                found = ["if (  ) {}", "other..."];
            }

            const result = {
                list: found,
                from: Pos(cur.line,token.start),
                to: Pos(cur.line, token.end),
            };
            callback(result);
        };
        hint.async = true;
        hint.supportsSelection = true;
        },

三、结果展示

1、图片展示

vue中codemirror自定义自动补全_第1张图片

你可能感兴趣的:(codemirror,javascript,前端)