api-client/components/ace-editor.vue

90 lines
1.6 KiB
Vue
Raw Normal View History

2019-11-09 19:28:05 +00:00
<template>
<pre ref="editor"></pre>
</template>
<script>
2020-02-24 18:44:50 +00:00
const DEFAULT_THEME = 'twilight'
2020-02-24 18:44:50 +00:00
import ace from 'ace-builds'
import 'ace-builds/webpack-resolver'
2019-11-09 19:28:05 +00:00
export default {
props: {
value: {
type: String,
2020-02-24 18:44:50 +00:00
default: '',
2019-11-09 19:28:05 +00:00
},
theme: {
type: String,
2020-02-24 18:44:50 +00:00
required: false,
2019-11-09 19:28:05 +00:00
},
lang: {
type: String,
2020-02-24 18:44:50 +00:00
default: 'json',
2019-11-09 19:28:05 +00:00
},
options: {
type: Object,
2020-02-24 18:44:50 +00:00
default: {},
},
2019-11-09 19:28:05 +00:00
},
data() {
return {
editor: null,
2020-02-24 18:44:50 +00:00
cacheValue: '',
}
2019-11-09 19:28:05 +00:00
},
watch: {
value(value) {
2019-11-12 04:52:50 +00:00
if (value !== this.cacheValue) {
2020-02-24 18:44:50 +00:00
this.editor.session.setValue(value, 1)
this.cacheValue = value
2019-11-09 19:28:05 +00:00
}
},
theme() {
2020-02-24 18:44:50 +00:00
this.editor.setTheme('ace/theme/' + this.defineTheme())
},
lang(value) {
2020-02-24 18:44:50 +00:00
this.editor.getSession().setMode('ace/mode/' + value)
},
options(value) {
2020-02-24 18:44:50 +00:00
this.editor.setOptions(value)
},
2019-11-09 19:28:05 +00:00
},
mounted() {
const editor = ace.edit(this.$refs.editor, {
2020-01-30 18:48:20 +00:00
theme: `ace/theme/${this.defineTheme()}`,
mode: `ace/mode/${this.lang}`,
2020-02-24 18:44:50 +00:00
...this.options,
})
2019-11-09 19:28:05 +00:00
2020-02-24 18:44:50 +00:00
if (this.value) editor.setValue(this.value, 1)
2019-11-09 19:28:05 +00:00
2020-02-24 18:44:50 +00:00
this.editor = editor
this.cacheValue = this.value
2019-12-10 16:28:08 +00:00
2020-02-24 18:44:50 +00:00
editor.on('change', () => {
const content = editor.getValue()
this.$emit('input', content)
this.cacheValue = content
})
},
methods: {
defineTheme() {
2020-01-31 12:55:55 +00:00
if (this.theme) {
2020-02-24 18:44:50 +00:00
return this.theme
2020-01-31 12:55:55 +00:00
}
2020-02-24 18:44:50 +00:00
return this.$store.state.postwoman.settings.THEME_ACE_EDITOR || DEFAULT_THEME
},
2019-11-09 19:28:05 +00:00
},
beforeDestroy() {
2020-02-24 18:44:50 +00:00
this.editor.destroy()
this.editor.container.remove()
},
}
2019-11-09 19:28:05 +00:00
</script>