Ace Editor for Vue.js

テキストエディタのAceをVue.js2.0のコンポーネントとして使う方法

by bc_rikko

HTML

<script src="https://rawgit.com/ajaxorg/ace-builds/master/src-min-noconflict/ace.js"></script>
<script src="https://unpkg.com/vue@2.0.1/dist/vue.js"></script>
<div id="app">
  <h1>Ace editor for Vue.js2.0 Components</h1>
  <p>Editor A</p>
  <div style="height: 100px">
    <editor editor-id="editorA" :content="contentA" v-on:change-content="changeContentA"></editor>
  </div>
  <p class="result">{{contentA}}</p>
  <p>Editor B</p>
  <div style="height: 100px">
    <editor editor-id="editorB" :content="contentB" v-on:change-content="changeContentB"></editor>
  </div>
  <p class="result">{{contentB}}</p>
  <button @click="reset">Reset</button>
</div>

CSS

.result {
   margin-top: 10px;
   background-color: #fff;
}

JavaScript

Vue.component('Editor', {
	template: '<div :id="editorId" style="width: 100%; height: 100%;"></div>',
  props: ['editorId', 'content', 'lang', 'theme'],
  data () {
    return {
      editor: Object,
      beforeContent: ''
    }
  },
  watch: {
    'content' (value) {
    	if (this.beforeContent !== value) {
      	this.editor.setValue(value, 1)
      }
    }
  },
  mounted () {
  	const lang = this.lang || 'text'
    const theme = this.theme || 'github'
  
		this.editor = window.ace.edit(this.editorId)
    this.editor.setValue(this.content, 1)
    
    // mode-xxx.js or theme-xxx.jsがある場合のみ有効
    this.editor.getSession().setMode(`ace/mode/${lang}`)
    this.editor.setTheme(`ace/theme/${theme}`)

    this.editor.on('change', () => {
    	this.beforeContent = this.editor.getValue()
      this.$emit('change-content', this.editor.getValue())
    })
  }
})


const app = new Vue({
	el: "#app",
  data () {
  	return {
      contentA: 'default content for Editor A',
      contentB: 'default content for Editor B'
    }
  },
  methods: {
  	reset () {
    	this.contentA = 'reset content for Editor A'
      this.contentB = 'reset content for Editor B'
    },
    changeContentA (val) {
    	if (this.contentA !== val) {
      	this.contentA = val
      }
    },
    changeContentB (val) {
    	if (this.contentB !== val) {
      	this.contentB = val
      }
    }
  }
})