您好,登錄后才能下訂單哦!
怎么在vue中利用monaco實現一個代碼高亮效果?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
Vue是一款友好的、多用途且高性能的JavaScript框架,使用vue可以創建可維護性和可測試性更強的代碼庫,Vue允許可以將一個網頁分割成可復用的組件,每個組件都包含屬于自己的HTML、CSS、JavaScript,以用來渲染網頁中相應的地方,所以越來越多的前端開發者使用vue。
首先需要下載monaco-editor組件,monaco-editor-webpack-plugin組件
npm install monaco-editor npm install monaco-editor-webpack-plugin
當然啦,npm下載很是緩慢,換個國內鏡像,淘寶的吧。果然,速度就嗖嗖的起來。
npm install -g cnpm --registry=https://registry.npm.taobao.org cnpm install cnpm install monaco-editor cnpm install monaco-editor-webpack-plugin
可在node_modules下看到其目錄結構
核心代碼如下所示
首先寫個組件,供其他頁面引入調用,
CodeEditor.vue
<template> <div class="code-container" ref="container"></div> </template> <script> import * as monaco from "monaco-editor"; let sqlStr = "ADD EXCEPT PERCENT ALL EXEC PLAN ALTER EXECUTE PRECISION AND EXISTS PRIMARY ANY EXIT PRINT AS FETCH PROC ASC FILE PROCEDURE AUTHORIZATION FILLFACTOR PUBLIC BACKUP FOR RAISERROR BEGIN FOREIGN READ BETWEEN FREETEXT READTEXT BREAK FREETEXTTABLE RECONFIGURE BROWSE FROM REFERENCES BULK FULL REPLICATION BY FUNCTION RESTORE CASCADE GOTO RESTRICT CASE GRANT RETURN CHECK GROUP REVOKE CHECKPOINT HAVING RIGHT CLOSE HOLDLOCK ROLLBACK CLUSTERED IDENTITY ROWCOUNT COALESCE IDENTITY_INSERT ROWGUIDCOL COLLATE IDENTITYCOL RULE COLUMN IF SAVE COMMIT IN SCHEMA COMPUTE INDEX SELECT CONSTRAINT INNER SESSION_USER CONTAINS INSERT SET CONTAINSTABLE INTERSECT SETUSER CONTINUE INTO SHUTDOWN CONVERT IS SOME CREATE JOIN STATISTICS CROSS KEY SYSTEM_USER CURRENT KILL TABLE CURRENT_DATE LEFT TEXTSIZE CURRENT_TIME LIKE THEN CURRENT_TIMESTAMP LINENO TO CURRENT_USER LOAD TOP CURSOR NATIONAL TRAN DATABASE NOCHECK TRANSACTION DBCC NONCLUSTERED TRIGGER DEALLOCATE NOT TRUNCATE DECLARE NULL TSEQUAL DEFAULT NULLIF UNION DELETE OF UNIQUE DENY OFF UPDATE DESC OFFSETS UPDATETEXT DISK ON USE DISTINCT OPEN USER DISTRIBUTED OPENDATASOURCE VALUES DOUBLE OPENQUERY VARYING DROP OPENROWSET VIEW DUMMY OPENXML WAITFOR DUMP OPTION WHEN ELSE OR WHERE END ORDER WHILE ERRLVL OUTER WITH ESCAPE OVER WRITETEXT"; export default { name: "codeEditor", props: { options: { type: Object, default() { return { language: "java", // shell、sql、python readOnly: true // 不能編輯 }; } }, value: { type: String, default: "" } }, data() { return { monacoInstance: null, provider: null, hints: [ "SELECT", "INSERT", "DELETE", "UPDATE", "CREATE TABLE", "DROP TABLE", "ALTER TABLE", "CREATE VIEW", "DROP VIEW", "CREATE INDEX", "DROP INDEX", "CREATE PROCEDURE", "DROP PROCEDURE", "CREATE TRIGGER", "DROP TRIGGER", "CREATE SCHEMA", "DROP SCHEMA", "CREATE DOMAIN", "ALTER DOMAIN", "DROP DOMAIN", "GRANT", "DENY", "REVOKE", "COMMIT", "ROLLBACK", "SET TRANSACTION", "DECLARE", "EXPLAN", "OPEN", "FETCH", "CLOSE", "PREPARE", "EXECUTE", "DESCRIBE", "FORM", "ORDER BY" ] }; }, created() { this.initHints(); }, mounted() { this.init(); }, beforeDestroy() { this.dispose(); }, methods: { dispose() { if (this.monacoInstance) { if (this.monacoInstance.getModel()) { this.monacoInstance.getModel().dispose(); } this.monacoInstance.dispose(); this.monacoInstance = null; if(this.provider){ this.provider.dispose(); this.provider = null } } }, initHints() { let sqlArr = sqlStr.split(" "); this.hints = Array.from(new Set([...this.hints, ...sqlArr])).sort(); }, init() { let that = this; this.dispose(); let createCompleters = textUntilPosition => { //過濾特殊字符 let _textUntilPosition = textUntilPosition .replace(/[\*\[\]@\$\(\)]/g, "") .replace(/(\s+|\.)/g, " "); //切割成數組 let arr = _textUntilPosition.split(" "); //取當前輸入值 let activeStr = arr[arr.length - 1]; //獲得輸入值的長度 let len = activeStr.length; //獲得編輯區域內已經存在的內容 let rexp = new RegExp('([^\\w]|^)'+activeStr+'\\w*', "gim"); let match = that.value.match(rexp); let _hints = !match ? [] : match.map(ele => { let rexp = new RegExp(activeStr, "gim"); let search = ele.search(rexp); return ele.substr(search) }) //查找匹配當前輸入值的元素 let hints = Array.from(new Set([...that.hints, ..._hints])).sort().filter(ele => { let rexp = new RegExp(ele.substr(0, len), "gim"); return match && match.length === 1 && ele === activeStr || ele.length === 1 ? false : activeStr.match(rexp); }); //添加內容提示 let res = hints.map(ele => { return { label: ele, kind: that.hints.indexOf(ele) > -1 ? monaco.languages.CompletionItemKind.Keyword : monaco.languages.CompletionItemKind.Text, documentation: ele, insertText: ele }; }); return res; }; this.provider = monaco.languages.registerCompletionItemProvider("sql", { provideCompletionItems(model, position) { var textUntilPosition = model.getValueInRange({ startLineNumber: position.lineNumber, startColumn: 1, endLineNumber: position.lineNumber, endColumn: position.column }); var suggestions = createCompleters(textUntilPosition); return { suggestions: suggestions }; return createCompleters(textUntilPosition); } }); // 初始化編輯器實例 this.monacoInstance = monaco.editor.create(this.$refs["container"], { value: this.value, theme: "vs-dark", autoIndex: true, ...this.options }); // 監聽編輯器content變化事件 this.monacoInstance.onDidChangeModelContent(() => { this.$emit("contentChange", this.monacoInstance.getValue()); }); } } }; </script> <style lang="scss" scope> .code-container { width: 100%; height: 100%; overflow: hidden; border: 1px solid #eaeaea; .monaco-editor .scroll-decoration { box-shadow: none; } } </style>
引入頁面,供本頁面使用
index.vue
<template> <div class="container"> <code-editor :options="options" :value="content" @contentChange="contentChange" ></code-editor> </div> </template> <script> import CodeEditor from "@/components/CodeEditor"; export default { name: "SQLEditor", components: { CodeEditor }, data() { return { content: "", options: { language: "sql", theme: 'vs', readOnly: false } }; }, created() {}, methods: { // 綁定編輯器value值的變化 contentChange(val) { this.content = val; } } }; </script> <style scoped lang="scss"> .container { text-align: left; padding: 10px; } </style>
效果如下所示
代碼自動提示效果,如下所示
代碼高亮效果,代碼段折疊效果,右側預覽效果如下所示
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。