codemirror6實現(xiàn)自定義代碼提示效果實例
1、需求
采用codemirror 6版本開發(fā) ,要求:自定義代碼提示 ,通過輸入關(guān)鍵字,實現(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 ,并添加對應(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)測 :
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)測得到的最新代碼
}),
],
parent: document.getElementById("coder"),
options: { },
});5、實現(xiàn)效果

總結(jié)
到此這篇關(guān)于codemirror6實現(xiàn)自定義代碼提示的文章就介紹到這了,更多相關(guān)codemirror6自定義代碼提示內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用three.js實現(xiàn)炫酷的酸性風(fēng)格3D頁面效果
本文內(nèi)容主要介紹,通過使用React+three.js技術(shù)棧,加載3D模型、添加3D文字、增加動畫、點擊交互等,配合樣式設(shè)計,實現(xiàn)充滿設(shè)計感的酸性風(fēng)格頁面2021-10-10

