codemirror6實(shí)現(xiàn)自定義代碼提示效果實(shí)例
1、需求
采用codemirror 6版本開發(fā) ,要求:自定義代碼提示 ,通過(guò)輸入關(guān)鍵字,實(shí)現(xiàn)代碼片段覆蓋。
類似于Vscode中輸入VueInit ,顯示代碼片段:
<template lang=""> <div> </div> </template> <script> export default { } </script> <style lang=""> </style>
參考官網(wǎng):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 ,并添加對(duì)應(yīng)id
const editor = new EditorView({ doc: "Press Ctrl-Space in here...\n", extensions: [ basicSetup, oneDark, ], parent: document.getElementById("coder"), options: {}, });
3、設(shè)置代碼提示
其中from為當(dāng)前位置 , options為自定義提示列表。apply 為需求中提到的自定義代碼,還有info 信息提示 等。
function myCompletions(context) { let word = context.matchBefore(/\w*/) if (word.from == word.to && !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、其他優(yōu)化
代碼回顯:
editor.dispatch({ changes: { from: 0, to: editor.state.doc.length, insert: content }, }); //插入content
以及代碼更新監(jiān)測(cè) :
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()) //監(jiān)測(cè)得到的最新代碼 }), ], parent: document.getElementById("coder"), options: { }, });
5、實(shí)現(xiàn)效果
總結(jié)
到此這篇關(guān)于codemirror6實(shí)現(xiàn)自定義代碼提示的文章就介紹到這了,更多相關(guān)codemirror6自定義代碼提示內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
原生JS實(shí)現(xiàn)ajax與ajax的跨域請(qǐng)求實(shí)例
下面小編就為大家分享一篇原生JS實(shí)現(xiàn)ajax與ajax的跨域請(qǐng)求實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2017-12-12使用three.js實(shí)現(xiàn)炫酷的酸性風(fēng)格3D頁(yè)面效果
本文內(nèi)容主要介紹,通過(guò)使用React+three.js技術(shù)棧,加載3D模型、添加3D文字、增加動(dòng)畫、點(diǎn)擊交互等,配合樣式設(shè)計(jì),實(shí)現(xiàn)充滿設(shè)計(jì)感的酸性風(fēng)格頁(yè)面2021-10-10uniapp時(shí)間格式和距離格式的轉(zhuǎn)換
這篇文章主要介紹了uniapp時(shí)間格式和距離格式的轉(zhuǎn)換,第一種是把? YYYY-MM-DD hh:mm:ss 轉(zhuǎn)換成?MM月DD日,第二種是把? hh:mm:ss 轉(zhuǎn)換成?hh:mm,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-09-09JS事件處理機(jī)制及事件代理(事件委托)實(shí)例詳解
這篇文章主要介紹了JS事件處理機(jī)制及事件代理,結(jié)合實(shí)例形式詳細(xì)分析了JS時(shí)間處理機(jī)制與事件代理功能、用法及相關(guān)使用技巧,需要的朋友可以參考下2023-06-06