Vue2 集成ace-editor实现代码编辑

1024刚刚过去,祝各位程序猿节日愉快呀(虽然我们公司毛活动都没搞…)
参考文章:

  1. Vue—加入ACE文本编辑器

1. 插件选取

实现代码编辑的插件有很多,code-mirrorace-editor等。最终选择了ace-editor
引入ace-editor的方式大致有三种:

  1. 从github下载build好的js,静态引入到项目中。这个我尝试了,但是require插件js的时候一直提示找不到,加上都用vue了还采用这种方式,感觉有点low,该方案就放弃了。
    静态引入
  2. 使用 vue2-ace-editor
    引入方式:
    npm install --save-dev vue2-ace-editor
    项目的@babel/core版本与他要求的不一样,安装后项目运行出错,最后也没采用。
  3. 使用 ace-builds
    引入方式:
    npm install ace-builds

2. 具体实现

2.1 初始化

<template>
  <div class="container">
    <div ref="ace" class="ace-editor"></div>
  </div>
</template>
<script>
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-dracula' // 主题
import 'ace-builds/src-noconflict/mode-html' // 语言模式
import 'ace-builds/src-noconflict/snippets/html' //代码提示
export default {
  name: 'ace-editor',
  data() {
    return {
      aceEditor: null
    }
  },
  methods: {
    initEditor() {
        // 初始化
       this.aceEditor = ace.edit(this.$refs.ace, {
        maxLines: 20, // 最大行数,超过会自动出现滚动条
        minLines: 20, // 最小行数,还未到最大行数时,编辑器会自动伸缩大小
        fontSize: 14, // 编辑器内字体大小
        theme: 'ace/theme/dracula', // 主题
        mode: 'ace/mode/html', // 默认设置的语言模式
        tabSize: 4, // 制表符设置为 4 个空格大小
      })
    }
 }
 </script>

2.2 常用方法

1. 代码提示

this.aceEditor.setOptions({
        enableSnippets: true,
         enableLiveAutocompletion: true,
         enableBasicAutocompletion: true
})

2. 编辑器只读

this.aceEditor.setReadOnly(true)

3. 隐藏打印线

this.aceEditor.setShowPrintMargin(false);
隐藏前:
打印线
隐藏后:
无打印线

4. 编辑器内容相关

  1. 编辑器内容变化的事件
  2. 获取编辑器内容
  3. 设置编辑器内容
 // 内容变化的事件:
 initEditor(){
 this.aceEditor.getSession().on('change', this.change)
 },
 change () {
      // 获取编辑器的内容
      this.$emit('input', this.aceEditor.getSession().getValue())
},
setValue(value){
      //设置编辑器内容
      this.aceEditor.setValue(value)
},

须知少时凌云志,曾许人间第一流。

—— 清·吴庆坻

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小雅痞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值