为什么要用ACE?
ACE方便页面上编写代码,能够提供JavaScript,SQL,Java等多种语言提示以及高亮显示,解析缩进等格式
欲知更多详情,文档在此:
中文文档:www.cnblogs.com/China-Dream…
官网:ace.c9.io/
git地址: github.com/ajaxorg/ace…
vue3中使用
先看效果
1.下载依赖包
npm install ace-builds --save-dev
node_modules下有四个版本的ace,具体区别如下:
2.主要说下语言提示功能的引入
- 语言默认为纯文本模式,其他语言需要作为单独模块引入
- 设置语言模式:
aceEditor.session.setMode('ace/mode/sql')
-
'ace/mode/sql'这个路径在 'ace-builds/webpack-resolver'里有转换,所以一定要引入'ace-builds/webpack-resolver'文件
-
当然,如果不想引入整个'ace-builds/webpack-resolver',也可以自己在组件单独写对应的路径处理
lua复制代码
ace.config.setModuleUrl('ace/mode/javascript', require('file-loader?esModule=false!ace-builds/src-noconflict/mode-javascript.js'));
3.完整代码
`<template>
<div :style="{'height': props.height,'width': props.width}" class="ace">
<el-form label-width="50px">
<el-form-item label="语言">
<el-select v-model="langType" @change="handleLang" style="width:120px;">
<el-option v-for="(item) in langArray" :key="item.name" :label="item.name" :value="item.path">
</el-option>
</el-select>
</el-form-item>
</el-form>
<div id="editor" ref="aceDom"></div>
</div>
</template>
<script setup lang="ts">
import { ref,onMounted } from "vue";
import ace from "ace-builds";
import 'ace-builds/webpack-resolver' // 在 webpack 环境中使用必须要导入
import 'ace-builds/src-noconflict/ext-language_tools'
import 'ace-builds/src-noconflict/theme-monokai' // 默认设置的主题
//自动提示规则
import 'ace-builds/src-noconflict/snippets/javascript'
import 'ace-builds/src-noconflict/snippets/sql'
import 'ace-builds/src-noconflict/snippets/json'
import 'ace-builds/src-noconflict/snippets/java'
import 'ace-builds/src-noconflict/snippets/text'
const props = defineProps(['height','width'])
const emit = defineEmits(['handleChange'])
const aceDom = ref()
let aceEditor:any = null
const langType = ref('')
const langArray = [
{
name: 'JavaScript',
path: 'ace/mode/javascript'
},
{
name: 'sql',
path: 'ace/mode/sql'
},
{
name: 'Json',
path: 'ace/mode/json'
},
{
name: 'Java',
path: 'ace/mode/java'
},
{
name: 'Text',
path: 'ace/mode/text'
}]
onMounted(() => {
init()
})
const init = () => {
// aceEditor = ace.edit("editor") //这里不用id,以防打包后容易出错
aceEditor = ace.edit(aceDom.value)
//提示功能
aceEditor.setOptions({
enableSnippets: true,
enableLiveAutocompletion: true,
enableBasicAutocompletion: true
})
//设置默认语言
langType.value = 'ace/mode/sql'
aceEditor.session.setMode('ace/mode/sql')
}
const handleLang = (val:string) => {
aceEditor.session.setMode(val)
}
const setVal = (val:string) => {
aceEditor.setValue(val)
}
//暴露方法
defineExpose({
setVal
});
</script>
<style scoped lang="scss">
.ace{
display: flex;
flex-direction: column;
#editor{
flex-grow:1;
margin:10px 0;
border:1px solid #c6e2ff;
}
}
</style>`
父组件调用: <Ace ref="aceChild" width="100%" :height="aceHeight" />