vue2-ace-editor 在线编辑器用法

发布于:2024-05-11 ⋅ 阅读:(26) ⋅ 点赞:(0)

先看效果

image.png

vue2-ace-editor简介

Ace 是一个用 JavaScript 编写的可嵌入代码编辑器。它与 Sublime、Vim 和 TextMate 等原生编辑器的功能和性能相匹配。它可以很容易地嵌入到任何网页和 JavaScript 应用程序中。Ace 被维护为Cloud9IDE的主要编辑器 ,并且是 Mozilla Skywriter (Bespin) 项目的继承者。

安装vue2-ace-editor依赖

npm install vue2-ace-editor --save

代码实例

ace-js.vue 组件代码

<template>
    <div class="codeEditBox" :style="{ height: height + 'px' }">
        <aceEditor ref="editor" :value="value" :lang="options.lang" :theme="theme" :options="options" @init="initEditor" v-bind="config">
        </aceEditor>
    </div>
</template>


<script>
//引入vue2-ace-editor
import aceEditor from 'vue2-ace-editor'
//引入ace 后续修改自定义标签用到
import ace from 'brace'
//代码提示
import 'brace/ext/language_tools'
import 'brace/mode/javascript'
import 'brace/snippets/javascript'
//搜索
import 'brace/ext/searchbox'
//主题
//白底色 带高亮
import 'brace/theme/chrome'
//白底色黑字  不带高亮
import 'brace/theme/github'
//黑底色
import 'brace/theme/tomorrow_night_eighties'
//蓝底色
import 'brace/theme/tomorrow_night_blue'
//黑底色
import 'brace/theme/vibrant_ink'

export default {
    name: 'Editor',
    components: {
        aceEditor
    },
    props: {
        value: {
            type: String,
            default: ''
        },
        height: {
            type: Number,
            default: 300
        },
        readOnly: {
            type: Boolean,
            default: false
        },
        theme: {
            type: String,
            default: 'chrome'
        },
        config: {
            type: Object,
            default: () => {
                return {
                    fontSize: 16
                }
            }
        }
    },
    computed: {
        options() {
            return {
                lang: 'javascript',//语言
                enableBasicAutocompletion: true,//启动代码补全功能
                enableSnippets: true,//启动代码段
                showPrintMargin: false,//显示打印边距
                fontSize: this.config.fontSize,//字体大小
                enableLiveAutocompletion: true,//启用实时自动完成
                readOnly: this.readOnly//只读
            }
        }
    },
    methods: {
        initEditor(editor) {
            //自定义标签
            const that = this
            const completer = {
                getCompletions: function (editors, session, pos, prefix, callback) {
                    that.setCompleteData(editors, session, pos, prefix, callback)
                }
            }
            const lnTools = ace.acequire('ace/ext/language_tools')
            lnTools.addCompleter(completer)
            // 监听值的变化
            editor.getSession().on('change', () => {
                this.$emit('change', editor.getValue())
            })
        },
        getValue() {//获取值
            return this.$refs.editor.editor.getValue()
        },
        setValue(value) {//赋值
            this.$refs.editor.editor.session.setValue(value)
        },
        clear() {//清空
            this.$refs.editor.editor.session.setValue('')
        },
        hasEditorError() {
            var annotations = this.$refs.editor.editor.getSession().getAnnotations();
            for (var aid = 0, alen = annotations.length; aid < alen; ++aid) {
                if (annotations[aid].type === 'error') {
                    return true;
                }
            }
            return false;
        },
        setCompleteData(editor, session, pos, prefix, callback) {
            const data = [
                {
                    meta: '方法名', // 描述
                    caption: 'get', // 展示出的名字(一般与value值相同)
                    value: 'function get(){}', // 数据值
                    score: 1 // 权重 数值越大 提示越靠前
                },
                {
                    meta: '方法名',
                    caption: 'set',
                    value: 'function set(){}',
                    score: 2
                }
            ]
            if (prefix.length === 0) {
                return callback(null, [])
            } else {
                return callback(null, data)
            }
        }
    }
}
</script>

index.vue 使用ace-js组件

<template>
    <div id="app">
        <div class="bwl-container">
            <el-card class="bwl-card1">
                <div class="bwl-card-header">
                    <el-select v-model="theme" style="width:130px;margin-right:6px;" size="small" placeholder="更换主体" filterable>
                        <el-option v-for="item in optionsTheme" :key="item.value" :value="item.value" :label="item.label"></el-option>
                    </el-select>
                    <el-select v-model="config.fontSize" style="width:130px;margin-right:6px;" size="small" placeholder="字体" filterable>
                        <el-option v-for="item in optionsFontSize" :key="item.value" :value="item.value" :label="item.label"></el-option>
                    </el-select>
                    <el-button type="primary" size="small" icon="el-icon-refresh-right" @click="onRun">运行</el-button>
                </div>


                <aceJs ref="aceJsRef" :height="500" :value="value" :config="config" :theme="theme" @change="onChange" :readOnly="false"></aceJs>
            </el-card>
            <el-card class="bwl-card2">
                <div id="myEcharts" style="width: 100%;height:600px"></div>
            </el-card>
        </div>
    </div>
</template>
<script>
import aceJs from './component/ace-js'
export default {
    name: 'aceEditor',
    components: {aceJs},
    data() {
        return {
            value: "",
            theme: 'chrome',
            content: "",
            chart: "",
            config: { fontSize: 14 },
            optionsTheme: [
                { value: 'chrome', label: 'chrome' },
                { value: 'vibrant_ink', label: 'vibrant_ink' },
                { value: 'tomorrow_night_eighties', label: 'tomorrow_night_eighties' },
                { value: 'github', label: 'githubcobalt' },
                { value: 'tomorrow_night_blue', label: 'tomorrow_night_blue' }],
            optionsFontSize: [{ value: 12, label: '12px' }, { value: 14, label: '14px' }, { value: 16, label: '16px' }, { value: 18, label: '18px' }]
        }
    },
   // mounted() {
   //   this.onRun();
   //  },
    methods: {
        onChange(value) {
            this.content = value;
        },

        onRun() {
            // 判断编辑器是否有误
            if (this.$refs["aceJsRef"].hasEditorError()) {
                this.$message.error('请检查代码是否正确');
                return;
            }

            // 初始化echart
            this.chart = this.$echarts.getInstanceByDom(document.getElementById("myEcharts"));
            if (this.chart == null) {

                this.chart = this.$echarts.init(document.getElementById("myEcharts"));
            }
            let option = {};
            let echarts = require("echarts")

            this.chart.clear();
            try {
                eval(this.content);

            } catch (err) {
                console.log("eval执行错误", err);
            }
            this.chart.setOption(option);
        },
    }
}
</script>
<style lang="scss" scoped>
.bwl-card-header {
    margin: 10px;
}

.bwl-container {
    display: flex;
    width: 100%;
    justify-content: space-around;

    .bwl-card1 {
        width: 50%;
    }

    .bwl-card2 {
        width: 50%;
    }
}
</style>

总结

北往是利用代码编辑器使用echarts在线编辑调试功能,index 页面结合echarts 初始化,实现个人项目需求; 根据个人需求进行vue2-ace-editor组件配置


网站公告

今日签到

点亮在社区的每一天
去签到