因为我的项目中须要在前端编写一些 yaml,json 格局的配置文件。一开始用的 codemirror 集成到我的项目中有很多问题, 故转而应用 ace Editor。
首先引入根本依赖
// 外围依赖
{src: 'https://cdn.bootcdn.net/ajax/libs/ace/1.4.9/ace.js'},
{src: 'https://cdn.bootcdn.net/ajax/libs/ace/1.4.9/ext-beautify.js'},
{src: 'https://cdn.bootcdn.net/ajax/libs/ace/1.4.9/ext-language_tools.js'},
// 编辑器主题,选本人须要的~~~~
{src: 'https://cdn.bootcdn.net/ajax/libs/ace/1.4.9/theme-xcode.js'},
// 语言反对,依据需要增加
{src: 'https://cdn.bootcdn.net/ajax/libs/ace/1.4.9/mode-yaml.js'},
{src: 'https://cdn.bootcdn.net/ajax/libs/ace/1.4.9/mode-javascript.js'},
{src: 'https://cdn.bootcdn.net/ajax/libs/ace/1.4.9/mode-json.js'},
编写组件(复制粘贴????)
<template>
<div ref="editor" :style="{height:height}" class="ace-editor" :id="Id"></div>
</template>
<script>
import uniqueId from 'lodash/uniqueId'
export default {
name: "AceEditor",
props:{
value:{
type:String,
default: ""
},
height:{
type:String,
default:"400px"
},
readOnly:{
type:Boolean,
default: false
},
mode:{
type:String,
default:"json"
}
},
mounted(){this.initEditor()
},
data(){
this.editor =null;
this.Id = uniqueId('aceEditor')
return{}},
computed:{
code:{ // 数据更新告诉父组件更新数据
set(val){this.$emit('input',val)
},
get(){return this.value}
},
},
watch:{code(){ // 父组件中数据变动,同步到 ace Editor
//aceEditor.setValue 调用后默认会全选所有文本内容,须要对光标进行非凡解决
// 缓存光标地位
const position = this.editor.getCursorPosition();
this.syncData()
this.editor.clearSelection();
this.editor.moveCursorToPosition(position);
},
mode(mode){this.changeMode(mode)
},
readOnly(b){this.setReadOnly(b)
}
},
methods: {initEditor(){this.editor = ace.edit(this.Id);
this.editor.setTheme('ace/theme/xcode');
// 编辑时同步数据
this.editor.session.on('change',(ev)=>{this.code = this.editor.getValue()
})
// 字体大小
this.editor.setFontSize(14)
this.syncData()
this.syncOptions()},
changeMode(modeName){
let mode ={
yaml:'ace/mode/yaml',
json:'ace/mode/json',
javascript:'ace/mode/javascript'
}
this.editor.session.setMode(mode[modeName]);
},
setReadOnly(readOnly){this.editor.setReadOnly(readOnly)
},
syncOptions(){this.setReadOnly(this.readOnly)
this.changeMode(this.mode)
},
syncData(){this.editor.setValue(this.code)
},
}
}
</script>
<style scoped>
.ace-editor{
position: relative;
height:300px;
border: 1px solid #ccc;
border-radius:2px;
}
.ace-editor /deep/ .ace_print-margin{display:none;}
</style>
应用
<ace-editor v-model="json" mode="json" ></cae-editor>