首先安装 ace-builds
“ace-builds”: “^1.24.0”
代码中
import { keywords } from '@/editor/data/option-keywords'
是自定义的代码提示配置文件
自定义代码提示文件内容如下图:
其实还可以添加一个代码格式化插件。
import beautify from 'js-beautify';
“js-beautify”: “^1.14.9”,
完整代码如下:
<template><div ref="ace_dom"></div>
</template>
<script setup lang="ts">
import ace from 'ace-builds'
import 'ace-builds/src-noconflict/mode-javascript'
import 'ace-builds/src-noconflict/snippets/javascript'
import 'ace-builds/src-noconflict/ext-language_tools'
import { onMounted, ref } from 'vue';
import { keywords } from '@/editor/data/option-keywords'
import beautify from 'js-beautify';const props = defineProps({modelValue: String
})const emit = defineEmits(['update:modelValue'])const ace_dom = ref(null)
onMounted(() => {const editor = ace.edit(ace_dom.value, {enableSnippets: true,enableBasicAutocompletion: true,enableLiveAutocompletion: true,maxLines: 50, // 最大行数,超过会自动出现滚动条minLines: 30, // 最小行数,还未到最大行数时,编辑器会自动伸缩大小fontSize: 14, // 编辑器内字体大小mode: 'ace/mode/javascript', // 默认设置的语言模式tabSize: 4, // 制表符设置为 4 个空格大小useWorker: false,value: props.modelValue || '', // 格式化代码的话这行代码就没必要存在了。})
// 如果需要格式化代码, 添加下面这代码
editor.setValue(beautify(props.modelValue || "", {/* 格式化代码配置项 */}), 1);const completions = keywords.map(keyword => ({caption: keyword.name,value: keyword.name,score: keyword.count,meta: 'local'}))ace.config.loadModule('ace/ext/language_tools', langTools => {langTools.addCompleter({getCompletions: function (editor, session, pos, prefix, callback) {callback(null, completions)}})})editor.getSession().on('change', () => emit('update:modelValue', editor.getValue().trim()))
})
</script>