最近用到了 Vue
页面使用 Yaml
编辑器,但是这样的组件也是从来没有接触过的,这边做个记载:
原文
# 安装必要依赖
npm install codemirrir@5.61.1
npm installl js-yaml@4.1.0
# 创建对应的组件
路径为 @/components/YamlEditor/index.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| <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')
export default { name: 'YamlEditor', 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', 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
的核心配置如下:
1 2 3 4 5 6 7
| this.yamlEditor = CodeMirror.fromTextArea(this.$refs.textarea, { lineNumbers: true, mode: 'text/x-yaml', gutters: ['CodeMirror-lint-markers'], theme: 'monokai', lint: true })
|
这里的配置只有几个简单的参数,更多的详细参数配置可以移步官方文档;如果想让编辑器支持其他语言,可以查看 codemirror 官方文档的语法支持,这里我个人比较倾向下载 codemirror
源码,可以看到对应语法 demo
源代码,使用不同的语法在本组件中 import
相应的依赖即可。
这边不同的主题: theme
# 使用组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| <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>
|
效果: