Ace Editor一款比较好用的展示代码组件

每天学一点

Winter

2021-09-06

最近在做项目需要展示代码片段,我们做的这个项目和eth区块浏览器的项目很像,之前也有用过一些代码展示的三方组件,但感觉会有点臃肿,看了etherscan上发现,还是它用的比较清爽也满足开发的需求。

 

先上图先给大家看看:

看了etherscan源码,发现他们用的是Ace editor。去看了源码后果断的就用起来了。

 

Ace官方文档:https://ace.c9.io/#nav=about&api=ace

Ace常用配置:https://github.com/ajaxorg/ace/wiki/Configuring-Ace

 

然后我用VUE封装了一个:

npm install vue2-ace-editor --save

 

组件代码

<template>
  <editor
    v-model="content"
    class="rounded-5 c-ace-editor" :lang="currentLang" :options="options"
    @init="editorInit"></editor>
</template>

<script>

export default {
  components: {
    editor: require('vue2-ace-editor'),
  },
  props: {
    lang: {
      type: String,
      default: 'javascript',
    },
    value: {
      type: String,
      default: '',
    },
    readOnly: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      content: this.value,
      isReadOnly: this.readOnly,
      currentLang: this.lang,
    };
  },
  computed: {
    options() {
      return {
        showFoldWidgets: true,
        showPrintMargin: false,
        foldStyle: 'markbegin',
        readOnly: this.isReadOnly,
      };
    },
  },
  watch: {
    value(val) {
      this.content = val;
    },
    readOnly(val) {
      this.isReadOnly = val;
    },
    lang(val) {
      this.currentLang = val;
    },
  },
  mounted() {

  },
  methods: {
    editorInit(editor) {
      require('brace/ext/language_tools'); // language extension prerequsite...
      require('brace/mode/javascript'); // language
      require('brace/mode/csharp'); // solidity和c#很像,etherscan用的也是这个模式
      require('brace/mode/json'); // language
      require('brace/theme/chrome');
      require('brace/snippets/javascript'); // snippet

      window.editor = editor;
    },
  },
};
</script>

 

第4290篇《Ace Editor一款比较好用的展示代码组件》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

0条评论