import * as monaco from 'monaco-editor'
import EditorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker'
import JsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker'
import { ref,onMounted,toRaw, onUnmounted } from "vue"
const isChange = () => {
monaco.languages.registerCompletionItemProvider('json', {
provideCompletionItems: (model, position) => {
// 获取当前行数
const line = position.lineNumber;
// 获取当前列数
const column = position.column;
// 获取当前输入行的所有内容
const content = model.getLineContent(line)
// 通过下标来获取当前光标后一个内容,即为刚输入的内容
const sym = content[column - 2];
const suggestions = ref(null);
if (sym === "") {
//拦截到用户输入$,开始设置提示内容,同else中代码一致,自行拓展
} else {
//直接提示,以下为sql语句关键词提示
suggestions.value = [
{
label: 'qqqqq',
kind: monaco.languages.CompletionItemKind.Function,
insertText: '""qqqqq":{\n\"type\":\"array\",\n\"items\":{}\n}"',
insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
detail: '返回指定参数的绝对值'
}
]
}
return {
suggestions: suggestions.value
};
},
triggerCharacters: ['$', ''],
});
}
onMounted(() => {
nextTick(initMonaco());
isChange()
})
出现的问题:
问题原因:registerCompletionItemProvider方法多次注册。
解决方法1:将注册方法放置在组件之外(.ts文件)
import * as monaco from 'monaco-editor';
import { ref} from "vue"
/**
* 注册:自定义语法补全
*/
export const registerProvider = () => {
const monacoProvider = monaco.languages.registerCompletionItemProvider('json', {
provideCompletionItems: () => {
let suggestions = ref(null);
suggestions.value = [
{
label: 'uploadFiles',
kind: monaco.languages.CompletionItemKind.Function,
insertText: '"uploadFiles":{"title": "上传文件","type": "string","ui:widget": "UploadWidget","ui:options":{"action": "/ab/api/v1/infrastructure/upload-file","btnText": "上传","style": {"width": "100%"}}}',
insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
detail: '返回指定参数的绝对值'
}
]
return {
suggestions: suggestions.value,
}
},
})
return monacoProvider
}
引入使用:
import { registerProvider } from '@/utils/monacoEditor'
const registerPro = registerProvider();
onMounted(() => {
nextTick(initMonaco());
registerPro;
})
解决方法2:销毁时使用dispose()
本人没有尝试这个方法;有兴趣可以参考文档:https://github.com/microsoft/monaco-editor/issues?page=52&q=is%3Aissue+is%3Aclosed
onUnmounted(() => {
registerPro.dispose()
})