一、前期准備
此組件的功能主要依賴於codemirror,另外加入了js-yaml進行語法檢查,方便在實時編輯時提示語法不正確的地方。因此首先需要在項目中安裝codemirror與js-yaml:
codemirror: npm install codemirror
js-yaml: npm install js-yaml --save
二、組件源碼及說明
新建@/components/YamlEditor/index.vue
文件:
<template>
<div class="yaml-editor">
<textarea ref="textarea" />
</div>
</template>
<script>
import CodeMirror from 'codemirror'
import 'codemirror/addon/lint/lint.css'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/monokai.css'
import 'codemirror/mode/yaml/yaml'
import 'codemirror/addon/lint/lint'
import 'codemirror/addon/lint/yaml-lint'
window.jsyaml = require('js-yaml') // 引入js-yaml為codemirror提高語法檢查核心支持
export default {
name: 'YamlEditor',
// eslint-disable-next-line vue/require-prop-types
props: ['value'],
data() {
return {
yamlEditor: false
}
},
watch: {
value(value) {
const editorValue = this.yamlEditor.getValue()
if (value !== editorValue) {
this.yamlEditor.setValue(this.value)
}
}
},
mounted() {
this.yamlEditor = CodeMirror.fromTextArea(this.$refs.textarea, {
lineNumbers: true, // 顯示行號
mode: 'text/x-yaml', // 語法model
gutters: ['CodeMirror-lint-markers'], // 語法檢查器
theme: 'monokai', // 編輯器主題
lint: true // 開啟語法檢查
})
this.yamlEditor.setValue(this.value)
this.yamlEditor.on('change', (cm) => {
this.$emit('changed', cm.getValue())
this.$emit('input', cm.getValue())
})
},
methods: {
getValue() {
return this.yamlEditor.getValue()
}
}
}
</script>
<style scoped>
.yaml-editor{
height: 100%;
position: relative;
}
.yaml-editor >>> .CodeMirror {
height: auto;
min-height: 300px;
}
.yaml-editor >>> .CodeMirror-scroll{
min-height: 300px;
}
.yaml-editor >>> .cm-s-rubyblue span.cm-string {
color: #F08047;
}
</style>
codemirror的核心配置如下:
this.yamlEditor = CodeMirror.fromTextArea(this.$refs.textarea, {
lineNumbers: true, // 顯示行號
mode: 'text/x-yaml', // 語法model
gutters: ['CodeMirror-lint-markers'], // 語法檢查器
theme: 'monokai', // 編輯器主題
lint: true // 開啟語法檢查
})
這里的配置只有幾個簡單的參數,個人認為有這些功能已經足夠了,更多的詳細參數配置可以移步官方文檔;如果想讓編輯器支持其他語言,可以查看codemirror官方文檔的語法支持,這里我個人比較傾向下載codemirror源碼,可以看到對應語法demo的源代碼,使用不同的語法在本組件中import相應的依賴即可。
三、組件使用
<template>
<div>
<div class="editor-container">
<yaml-editor v-model="value" />
</div>
</div>
</template>
<script>
import YamlEditor from '@/components/YamlEditor/index.vue';
const yamlData = "- hosts: all\n become: yes\n become_method: sudo\n gather_facts: no\n\n tasks:\n - name: \"install {{ package_name }}\"\n package:\n name: \"{{ package_name }}\"\n state: \"{{ state | default('present') }}\"";
export default {
name: 'YamlEditorDemo',
components: { YamlEditor },
data() {
return {
value: yamlData,
};
},
};
</script>
<style scoped>
.editor-container{
position: relative;
height: 100%;
}
</style>
四、效果截圖