Vue + monaco-editor
生活随笔
收集整理的這篇文章主要介紹了
Vue + monaco-editor
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
提示:文章寫完后,目錄可以自動生成,如何生成可參考右邊的幫助文檔
文章目錄
- 前言
- 一、monaco-editor是什么?
- 二、使用步驟
- 1.安裝依賴
- 2.編寫組件
- 3.自定義提示
- 總結
前言
最近接手了一個新項目,這個項目中有一個需求點就是需要展示json,并且可能還要編輯展示代碼,然后我就去調研了關于代碼編輯器的有關技術,經過對比決定使用monaco-editor。
提示:以下是本篇文章正文內容,下面案例可供參考
一、monaco-editor是什么?
monaco-editor一款代碼編輯器,是微軟開源的一個web編輯器,vscode中也是集成它來實現的,所以我們可以通過monaco-editor在我們的網頁中集成一個vscode出來,好的廢話不多說,直接開干。
二、使用步驟
1.安裝依賴
yarn add monaco-editor 或 npm i monaco-editor2.編寫組件
我的代碼如下:
<div ref="json-editor-code" class="json-editor"></div> @Component export default class JsonCodeEditor extends Vue {@Prop({ default: () => {} }) private data!: any@Prop({ default: () => {} }) private opt?: anyprivate editor: any;private monaco: any= monaco;private options: any = {language: 'json', // 這里你可以自己寫語言。我是寫死了。automaticLayout: true,tabSize: 2,overviewRulerBorder: false,scrollBeyondLastLine: false,minimap: {enabled: false // 不要小地圖},theme: 'vs',fontSize: "14px",autoIndent:true,//自動布局}@Watch('data', { deep: true })private activeChange(val: any) {let current: any = this.jsonValidator(this.editor.getValue())if (current && !isEqual(val, current)) {this.editor.setValue(JSON.stringify(val))this.format()}}// json格式檢查private jsonValidator(val: string) {let parsedValuetry {parsedValue = JSON.parse(val)return parsedValue} catch (e) {return false}}private mounted() {this.initEditor()setTimeout(()=>{this.format()},100)}private initEditor() {let container = (this.$refs['json-editor-code'] as HTMLElement);this.editor = this.monaco.editor.create(container, {value: JSON.stringify(this.data),//編輯器初始顯示文字...Object.assign(this.options, this.opt),scrollbar: {horizontal: 'hidden',}})this.editor.onDidChangeModelContent(() => {this.$emit('code-change', this.jsonValidator(this.editor.getValue()), this.editor, this.monaco)})}private destroyed() {this.editor?.dispose()}private format() {this.editor.getAction('editor.action.formatDocument').run()} }自此我們就完成一個編輯器組件的一次簡單封裝。
3.自定義提示
如果我們想要自定義代碼提示,并且還能自定義提示警告那該怎么辦呢?
其實官方給我們提供了一個演示的demo,但是我沒有直接跑出來,經過我的摸索也算是實現了,附上schema規則書寫文檔和一個能在線生成規則的網站。接下來請看,假設規則如下:
那么我們封裝一個函數用于獲取規則
private getRule(type) {return validators.find((vd: any) => vd.name === type);}private switchRules(val: any) {let ruleArray = getRule(val.type)ruleArray = Object.assign(cloneDeep(ruleArray), { fileMatch: ['*'] }) // 這里不可少 this.monaco.languages.json.jsonDefaults.setDiagnosticsOptions({validate: true,schemas: cloneDeep(ruleArray)})}獲取規則的函數我們有了以后,只需要在數據改變的時候調用這個方法即可更新成匹配當前數據的規則了。
@Watch('data', { deep: true })private activeChange(val: any) {let current: any = this.jsonValidator(this.editor.getValue())if (current && !isEqual(val, current)) {this.switchRules(val) // 這樣就更新了規則this.editor.setValue(JSON.stringify(val))this.format()}}總結
monaco還是有缺陷的,比如你的規則會被多個monaco-editor實例共享,不過只要你手動去除就好了,這點也還是能接收。希望這篇文章能夠幫助到你。喜歡的話記得一鍵三連。
總結
以上是生活随笔為你收集整理的Vue + monaco-editor的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Tomcat内存大小配置
- 下一篇: python实现隐函数曲率求解