search
HomeWeb Front-endVue.jsDetailed graphic explanation of how to integrate the Ace code editor in a Vue project


Preface

In the process of integrating Ace, I found that the information found on the Internet is relatively fragmented, and there are relatively few Chinese materials. This article mainly records and organizes it to facilitate subsequent reference

  • Integrating the Ace code editor into the Vue project
  • Chinese comparison of Ace configuration items
  • Stepping into the trap: Solving the Ace editor cursor misalignment problem
  • Optimization: Use ace-builds on demand

Introduction

Ace is an embeddable code editor written in JavaScript. It matches the functionality and performance of native editors like Sublime, Vim, and TextMate. It can be easily embedded into any web page and JavaScript application. Ace is maintained as the primary editor for the Cloud9 IDE and is the successor to the Mozilla Skywriter (Bespin) project.

Features

  • Syntax highlighting for over 110 languages(Can import TextMate/Sublime Text .tmlanguage files)
  • More than 20 themes (can import TextMate/Sublime Text .tmtheme files)
  • Automatic indentation and upgrade
  • An optional command line
  • processing Huge documentation (four million lines seems to be the limit!)
  • Fully customizable keybindings, including vim and Emacs modes
  • Search and replace using regular expressions
  • Highlight matching brackets
  • Switch between soft tabs and real tabs
  • Show hidden characters
  • Use mouse to drag and drop text
  • Wrap lines
  • Code folding
  • Multiple cursors and selections
  • Live syntax checker (currently JavaScript/CoffeeScript/CSS/XQuery)
  • Cut, copy and paste function

Quick start

  • You can also use vue2-ace-editor directly and follow the steps to integrate
  • Here we mainly record the use of ace-builds and encapsulate the Ace components in the project

Installation

npm install ace-builds --save-dev复制代码

The effect after installation is as follows:

Detailed graphic explanation of how to integrate the Ace code editor in a Vue project

Integration

Create a new folder AceEditor

Detailed graphic explanation of how to integrate the Ace code editor in a Vue project

##In the AceEditor file, create a new index.vue, the code is as follows:

<template>
  <div
    ref="editorform"
   
    style="height: 250px"
  >
  </div>
</template>

<script>
import ace from &#39;ace-builds&#39;
import &#39;./webpack-resolver&#39; // 自定义webpack-resolver,按需引入
import &#39;ace-builds/src-noconflict/mode-json&#39;
import &#39;ace-builds/src-noconflict/mode-mysql&#39;
import &#39;ace-builds/src-noconflict/mode-text&#39;
import &#39;ace-builds/src-noconflict/theme-tomorrow&#39;
import &#39;ace-builds/src-min-noconflict/ext-language_tools&#39;
import { onMounted, onBeforeUnmount, ref, watch } from &#39;@vue/composition-api&#39;

export default {
  name: &#39;AceEditor&#39;,
  emits: [&#39;onChange&#39;],
  props: {
    value: {
      type: String,
      default: &#39;&#39;,
    },
    // 这里可以接收更多组件传递的参数,做一些自定义效果
  },
  setup(props, vm) {
    let editor = null
    const editorform = ref(null)
    let options = {
      theme: &#39;ace/theme/tomorrow&#39;, // 主题
      mode: &#39;ace/mode/mysql&#39;, // 代码匹配模式
      tabSize: 2, //标签大小
      fontSize: 14, //设置字号
      wrap: true, // 用户输入的sql语句,自动换行
      enableSnippets: true, // 启用代码段
      showLineNumbers: true, // 显示行号
      enableLiveAutocompletion: true, // 启用实时自动完成功能 (比如:智能代码提示)
      enableBasicAutocompletion: true, // 启用基本自动完成功能
      scrollPastEnd: true, // 滚动位置
      highlightActiveLine: true, // 高亮当前行
    }

    const init = () => {
      if (editor) {
        //实例销毁
        editor.destroy()
      }
      //初始化
      editor = ace.edit(editorform.value, options)
      editor.setValue(props.value ? props.value : &#39;&#39;) // 设置内容
      editor.on(&#39;change&#39;, () => {
        vm.emit(&#39;onChange&#39;, editor.getValue())
      })
    }
    
    onMounted(() => {
      init()
    })
    
    onBeforeUnmount(() => {
      editor.destroy()
      editor.container.remove()
    })
    return {
      editorform
    }
  },
}
</script>

<style>
@import &#39;~ace-builds/css/ace.css&#39;;
</style>

About the optimization of webpack-resolver.js

In the webpack environment, webpack-resolver.js needs to be imported. Let’s take a look at node_modules/ace-builds/webpack-resolver first. .js file, most of the modules in it are not used by us. If imported directly, it will greatly increase the size of the project package, so we need to do some optimization here:

Introduce on demandIn the AceEditor file , create a new webpack-resolver.js, the code is as follows: Detailed graphic explanation of how to integrate the Ace code editor in a Vue project

ace.config.setModuleUrl(&#39;ace/mode/mysql&#39;, require(&#39;file-loader?esModule=false!ace-builds/src-noconflict/mode-mysql.js&#39;))
ace.config.setModuleUrl(&#39;ace/mode/text&#39;, require(&#39;file-loader?esModule=false!ace-builds/src-noconflict/mode-text.js&#39;))
ace.config.setModuleUrl(&#39;ace/mode/json&#39;, require(&#39;file-loader?esModule=false!ace-builds/src-noconflict/mode-json.js&#39;))
ace.config.setModuleUrl(&#39;ace/theme/tomorrow&#39;, require(&#39;file-loader?esModule=false!ace-builds/src-noconflict/theme-tomorrow.js&#39;))
ace.config.setModuleUrl(&#39;ace/ext/language_tools&#39;, require(&#39;file-loader?esModule=false!ace-builds/src-noconflict/ext-language_tools.js&#39;))

In the src directory of the project, create a new registerAce.js

import ACE from &#39;@/components/AceEditor&#39; // 这里是你创建的AceEditor文件夹的路径
 
export default {
  install(Vue) {
    Vue.component(&#39;ace&#39;, ACE)
  },
}

Introduce the Ace module into the entry file main.js of the Vue project, Vue.use() globally registers ace components

import ace from &#39;ace-builds&#39;
import RegistAce from &#39;./registAce&#39;

Vue.use(ace)
Vue.use(RegistAce)

Use ace components (global components)

<ace v-model="content" @onChange="onChange"> </ace>

Above, the simple integration of Ace is completed in the Vue project. For more functions, please refer to the official website :

Ace official website

Configuration items

Official website wiki:

github.com/ajaxorg/ace…

Core ace components (

editor, session, renderer, mouseHandler) implement optionProvider interface

setOption(optionName, optionValue)
setOptions({
    optionName : optionValue
    ...
})
getOption(optionName)
getOptions()

The following are List of configuration options. Unless otherwise stated, option values ​​are Boolean.

editor.setOption will also modify session/renderer/$mouseHandleroptions associated with it

editor options
##selectionStyleStringtextline | textSelected stylehighlightActiveLineBooleantrue-Highlight the current linehighlightSelectedWordBooleantrue-Highlight selected textreadOnlyBooleanfalse-Whether it is read onlycursorStyleStringaceace | slim | smooth | wideCursor stylemergeUndoDeltasString | BooleanfalsealwaysMerge UndobehavioursEnabledBooleantrue-Enable BehaviorwrapBehavioursEnabledBooleantrue-Enable line wrappingautoScrollEditorIntoViewBooleanfalse-Enable scrollingcopyWithEmptySelectionBooleantrue-Copy spacesuseSoftTabsBooleanfalse-Use SoftTabs navigateWithinSoftTabsBooleanfalse-Soft tab jumpenableMultiselectBooleanfalse-Select multiple places
Option name Value type Default value Optional value Function
renderer options
Option nameValue typeDefault valueOptional valueFunctionhScrollBarAlwaysVisibleBooleanfalse-The vertical scroll bar is always visiblevScrollBarAlwaysVisibleBooleanfalse-The horizontal scroll bar is always visiblehighlightGutterLine Booleantrue-Highlighted EdgeanimatedScrollBoolean false-Scroll animationshowInvisiblesBooleanfalse-Show invisible charactersshowPrintMarginBooleantrue- Display print marginsprintMarginColumnNumber80- Set page marginprintMarginBoolean | Numberfalse-Display and set page MarginfadeFoldWidgetsBooleanfalse-Fade FoldWidgetsshowFoldWidgetsBooleantrue-Show FoldWidgets showLineNumbersBooleantrue-show line numbershowGutter Booleantrue-Display line number area##displayIndentGuidesfontSizefontFamilymaxLinesminLinesscrollPastEndfixedWidthGutterthememouseHandler options
Boolean true - Show reference line
Number | String inherit - Set font size
String inherit
Set font
Number - - Maximum number of lines
Number - - At least the number of lines
Boolean | Number 0 - Scroll Position
Boolean false - Fixed line number area width
String - - Theme reference path, such as "ace/theme/textmate"
Option namescrollSpeeddragDelaydragEnabledfocusTimouttooltipFollowsMouse
session options
Value type Default value Optional value Remarks
Number - - Scroll Speed
Number - - Drag Delay
Boolean true - Whether drag is enabled
Number - - Focus Timeout
Boolean false - Mouse Tip
Option name Value type Default value Optional value Remarks
firstLineNumber Number 1 - Starting line number
overwrite Boolean - - Redo
newLineMode String auto auto | unix | windows New Line Mode
useWorker Boolean - - Use helper objects
useSoftTabs Boolean - - Use soft tags
tabSize Number - - Tag size
wrap Boolean - - Line break
foldStyle String - markbegin | markbeginend | manual Collapse style
mode String - - Code Match pattern, such as "ace/mode/text"
editor options defined by extensions
Option name Value type Default value Optional value Remarks
enableBasicAutocompletion Boolean - - Enable Basic Autocompletion
enableLiveAutocompletion Boolean - - Enable real-time autocomplete
enableSnippets Boolean - - Enable snippet
enableEmmet Boolean - - Enable Emmet
useElasticTabstops Boolean - - use Flexible tab stops

Solving the problem of cursor misalignment

When inputting content in the editor, the problem of cursor misalignment will occur. It initially looks like Normally, the more content you input, the more the cursor will be misaligned. Detailed graphic explanation of how to integrate the Ace code editor in a Vue project After troubleshooting, it was found that the calculation was inaccurate because of the use of non-monospaced fonts. Set the font in the edit box to Monowidth font can solve the problem

⚠️Note: There is still a small pit here. When setting the monowidth font, you need to distinguish between Mac and Windows

  • Can be done under Mac Use monospace font
  • You can use Consolas font under Windows

Reference website/source code

The above is the detailed content of Detailed graphic explanation of how to integrate the Ace code editor in a Vue project. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:juejin. If there is any infringement, please contact admin@php.cn delete
React vs. Vue: Which Framework Does Netflix Use?React vs. Vue: Which Framework Does Netflix Use?Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

The Choice of Frameworks: What Drives Netflix's Decisions?The Choice of Frameworks: What Drives Netflix's Decisions?Apr 13, 2025 am 12:05 AM

Netflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.

React, Vue, and the Future of Netflix's FrontendReact, Vue, and the Future of Netflix's FrontendApr 12, 2025 am 12:12 AM

Netflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.

Vue.js in the Frontend: Real-World Applications and ExamplesVue.js in the Frontend: Real-World Applications and ExamplesApr 11, 2025 am 12:12 AM

Vue.js is a progressive JavaScript framework suitable for building complex user interfaces. 1) Its core concepts include responsive data, componentization and virtual DOM. 2) In practical applications, it can be demonstrated by building Todo applications and integrating VueRouter. 3) When debugging, it is recommended to use VueDevtools and console.log. 4) Performance optimization can be achieved through v-if/v-show, list rendering optimization, asynchronous loading of components, etc.

Vue.js and React: Understanding the Key DifferencesVue.js and React: Understanding the Key DifferencesApr 10, 2025 am 09:26 AM

Vue.js is suitable for small to medium-sized projects, while React is more suitable for large and complex applications. 1. Vue.js' responsive system automatically updates the DOM through dependency tracking, making it easy to manage data changes. 2.React adopts a one-way data flow, and data flows from the parent component to the child component, providing a clear data flow and an easy-to-debug structure.

Vue.js vs. React: Project-Specific ConsiderationsVue.js vs. React: Project-Specific ConsiderationsApr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

How to jump a tag to vueHow to jump a tag to vueApr 08, 2025 am 09:24 AM

The methods to implement the jump of a tag in Vue include: using the a tag in the HTML template to specify the href attribute. Use the router-link component of Vue routing. Use this.$router.push() method in JavaScript. Parameters can be passed through the query parameter and routes are configured in the router options for dynamic jumps.

How to implement component jump for vueHow to implement component jump for vueApr 08, 2025 am 09:21 AM

There are the following methods to implement component jump in Vue: use router-link and <router-view> components to perform hyperlink jump, and specify the :to attribute as the target path. Use the <router-view> component directly to display the currently routed rendered components. Use the router.push() and router.replace() methods for programmatic navigation. The former saves history and the latter replaces the current route without leaving records.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool