vue中codemirror自定义自动补全

本文介绍了如何在Vue应用中使用vue-codemirror插件,并展示了如何设置自动提示功能,以便于开发者实时获得JavaScript和SQL的代码建议。通过实例代码和配置,提升代码编辑体验。

一、下载并引入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、图片展示

在这里插入图片描述

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值