vue3插件:ace-builds封装ace-editor

安装包

npm install ace-builds --save-dev
//引入ace报错需要安装
npm install vue-loader-v16 -D

封装文件

ace-editor相关文档参考

webpack环境必备:import "ace-builds/webpack-resolver";
非webpack环境不需要引入

<template>
  <div ref="editorform" style="height: 300px" class="ace-editor"></div>
</template>
<script>
import { watch, onMounted, onBeforeUnmount, ref} from "vue";
import ace from "ace-builds";
import "ace-builds/webpack-resolver";
import "ace-builds/src-noconflict/mode-yaml";
import "ace-builds/src-noconflict/theme-chaos";
import "ace-builds/src-noconflict/ext-language_tools";
import "ace-builds/src-noconflict/ext-emmet";
import "ace-builds/src-noconflict/snippets/yaml";
//import "ace-builds/src-noconflict/keybinding-vscode";
//import "ace-builds/src-noconflict/keybinding-emacs";
export default {
  name: "CodeEditor",
  emits: ["update:value"],
  props: {
    id: {
      type: Number,
      default: 0,
    },
    // 外部传入的内容,用于实现双向绑定
    value: {
      type: String,
      default: "",
    },
    readonly: {
      type: Boolean,
      default: false,
    },
    // 外部传入的语法类型
    language: {
      type: String,
      default: "yaml",
    },
    // 编辑器主题色
    theme: {
      type: String,
      default: "chaos",
    },
  },
  setup(props, { emit }) {
    let editor = null;
    const editorform = ref(null);
    let options = {
      theme: "ace/theme/" + (props.theme ? props.theme : "chaos"),
      mode: "ace/mode/" + (props.language ? props.language : "yaml"),
      tabSize: 2,
      maxLines: 25,
      minLines: 25,
      showPrintMargin: false,
      fontSize: 14,
      readOnly: props.readonly ? props.readonly : false,
    };
    //切换语言
    //editor.getSession().setMode(modelPath)

    function initialize() {
      if (editor) {
        //实例销毁
        editor.destroy();
      }
      //初始化
      editor = ace.edit(editorform.value, options);
      //代码提示和自动补全
      editor.setOptions({
        enableSnippets: true,
        enableLiveAutocompletion: true,
        enableBasicAutocompletion: true,
      });
      editor.getSession().setUseWrapMode(true);
      // 支持双向绑定
      editor.on("change", () => {
        if (emit) {
          emit("update:value", editor.getValue());
        }
      });
       //快捷键
      editor.commands.addCommand({
        name: 'formatter',
        bindKey: { win: 'Ctrl-Shift-F', mac: 'Command-Shift-F' },
        exec: () => emit('formatter', editor)
      })
      editor.setValue(props.value ? props.value : "");
    }
    watch(
      () => props.id,
      () => {
        initialize();
      }
    );
    watch(
      () => props.value,
      (newProps) => {
        //解决光标移动问题
        const position = editor.getCursorPosition();
        editor.getSession().setValue(newProps);
        editor.clearSelection();
        editor.moveCursorToPosition(position);
      }
    );
    onMounted(() => {
      initialize();
    });
    onBeforeUnmount(() => {
      editor.destroy();
    });
    return {
      editorform,
    };
  },
};
</script>
<style lang="scss" scoped>
    .ace-chaos .ace_meta.ace_tag{
        color:#53a7e6 !important;
    }
    .ace-chaos .ace_string{
        color:#c58854 !important;
    }
    .ace-chaos .ace_keyword{
        color:#e0e0e0 !important;
    }
    .ace-chaos .ace_constant.ace_numeric{
        color:#c5c454 !important;
    }
</style>

###页面使用

<!--解决视图更新问题-->
<!--@update:value="cmadd.value = $event"-->
<template>
<div>
  <code-editor
        ref="addcodeform"
        v-model:value="cmadd.value"
        v-model:id="cmadd.id"
        @update:value="cmadd.value = $event"
      ></code-editor>
</div>
</template>
<script>
import {ref} from "vue";
import CodeEditor from "@/components/AceEditor";
export default {
  components:{CodeEditor},
  setup(){
    const cmadd=ref({value:"",id:0});
    return{cmadd}
  }
}
</script>
  • 10
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
1. 安装 vue3-ace-editor ```shell npm install vue3-ace-editor ``` 2. 在需要使用的组件中引入 ace-editor 组件 ```html <template> <AceEditor v-model="code" :options="options" mode="myCustomLanguage" :highlightActiveLine="true" :tabSize="2" theme="twilight" style="height: 500px;" /> </template> <script> import AceEditor from "vue3-ace-editor"; export default { components: { AceEditor, }, data() { return { code: "", options: { enableBasicAutocompletion: true, enableSnippets: true, enableLiveAutocompletion: true, }, }; }, mounted() { this.$nextTick(() => { this.code = "function myFunction() {\n console.log('Hello World!');\n}"; }); }, }; </script> ``` 3. 添加自定义语言 ```javascript import ace from "ace-builds"; import "ace-builds/src-noconflict/mode-javascript"; // 引入 JavaScript 语言模块 ace.define( "ace/mode/myCustomLanguage_highlight_rules", function (require, exports) { var oop = require("ace/lib/oop"); var TextHighlightRules = require("ace/mode/text_highlight_rules") .TextHighlightRules; var MyCustomLanguageHighlightRules = function () { // 注释 this.$rules["start"] = [ { token: "comment", regex: "//.*$", }, ]; // 关键字 this.$rules["start"].push({ token: "keyword", regex: "function", }); // 函数名 this.$rules["start"].push({ token: "entity.name.function", regex: "myFunction", }); // 字符串 this.$rules["start"].push({ token: "string", regex: "'|\"", next: "string", }); // 其他 this.$rules["start"].push({ defaultToken: "text", }); this.$rules.string = [ { token: "constant.language.escape", regex: /\\(?:['"\\]|[0-7]{3})/, }, { token: "string", regex: /['"]/, next: "start", }, { defaultToken: "string", }, ]; }; oop.inherits(MyCustomLanguageHighlightRules, TextHighlightRules); exports.MyCustomLanguageHighlightRules = MyCustomLanguageHighlightRules; } ); ace.define("ace/mode/myCustomLanguage", function (require, exports) { var oop = require("ace/lib/oop"); var TextMode = require("ace/mode/text").Mode; var MyCustomLanguageHighlightRules = require("./myCustomLanguage_highlight_rules") .MyCustomLanguageHighlightRules; var MyCustomLanguageMode = function () { this.HighlightRules = MyCustomLanguageHighlightRules; }; oop.inherits(MyCustomLanguageMode, TextMode); (function () { this.$id = "ace/mode/myCustomLanguage"; }).call(MyCustomLanguageMode.prototype); exports.Mode = MyCustomLanguageMode; }); ``` 4. 在组件中引入自定义语言模块 ```javascript import "ace-builds/src-noconflict/mode-myCustomLanguage"; // 引入自定义语言模块 ``` 5. 完整代码 ```html <template> <AceEditor v-model="code" :options="options" mode="myCustomLanguage" :highlightActiveLine="true" :tabSize="2" theme="twilight" style="height: 500px;" /> </template> <script> import AceEditor from "vue3-ace-editor"; import "ace-builds/src-noconflict/mode-myCustomLanguage"; // 引入自定义语言模块 export default { components: { AceEditor, }, data() { return { code: "", options: { enableBasicAutocompletion: true, enableSnippets: true, enableLiveAutocompletion: true, }, }; }, mounted() { this.$nextTick(() => { this.code = "function myFunction() {\n console.log('Hello World!');\n}"; }); }, }; </script> ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值