Ace Editor for Vue.js
by Justin Chen
HTML
<script src="https://rawgit.com/ajaxorg/ace-builds/master/src-min-noconflict/ace.js"></script>
<script src="https://unpkg.com/[email protected]/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>
<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 || 'json'
const theme = this.theme || 'github'
this.editor = window.ace.edit(this.editorId)
this.editor.setValue(this.content, 0)
// 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: JSON.stringify({
test: 1,
str: '2222'
}, null, '\t')
}
},
methods: {
reset() {
this.contentA = JSON.stringify({
"title": "Person",
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"age": {
"description": "Age in years",
"type": "integer",
"minimum": 0
}
},
"required": ["firstName", "lastName"]
}, null, '\t')
},
changeContentA(val) {
if (this.contentA !== val) {
this.contentA = val
}
}
}
})