<template> <div class="dee-code-edit-com"> <textarea ref="mycode" v-model="textarea" class="textarea" /> </div> </template> <script> import 'codemirror/lib/codemirror.css' // load model import 'codemirror/mode/javascript/javascript' import 'codemirror/mode/javascript/javascript' // load codetip import 'codemirror/addon/hint/show-hint.css' import 'codemirror/addon/hint/show-hint' import 'codemirror/theme/3024-night.css' import 'codemirror/mode/clike/clike.js' const CodeMirror = require('codemirror') require('codemirror/addon/edit/matchbrackets') require('codemirror/addon/selection/active-line') require('codemirror/mode/javascript/javascript') require('codemirror/addon/hint/show-hint') require('codemirror/keymap/sublime.js') require('codemirror/addon/selection/active-line.js') require('codemirror/addon/edit/matchbrackets.js') require('codemirror/addon/display/autorefresh.js') export default { name: 'DeeCodeEdit', components: { }, props: { value: { type: String, default: () => '' }, mode: { type: String, default: () => 'javascript' } }, data() { return { textarea: '', code: '', editorText: '', cmOptions: { } } }, watch: { value: { handler: function(val) { if (val !== this.code) { this.setValue(val) } }, immediate: true } }, mounted() { this.editorText = CodeMirror.fromTextArea(this.$refs.mycode, { mode: { name: this.mode, globalVars: true }, theme: '3024-night', indentWithTabs: true, smartIndent: true, lineNumbers: true, matchBrackets: true, autoRefresh: true, extraKeys: { Ctrl: 'autocomplete' }, // 自定义快捷键 hintOptions: { // 自定义提示选项 tables: { users: ['name', 'score', 'birthDate'], countries: ['name', 'population', 'size'] } } }) this.$nextTick(() => { this.editorText.setValue(this.value) this.refresh() }) // 可选,挂载一下监听事项 this.editorText.on('change', (cm) => { this.code = cm.getValue() // 这里要用多一个载体去获取值,不然会重复赋值卡顿 this.$emit('input', cm.getValue()) }) }, methods: { debounce(func, wait = 0) { if (typeof func !== 'function') { throw new TypeError('need a function arguments') } let timeid = null let result return function() { const context = this const args = arguments if (timeid) { clearTimeout(timeid) } timeid = setTimeout(function() { result = func.apply(context, args) }, wait) return result } }, refresh() { this.$nextTick(() => { this.editorText.refresh() }) }, setValue(value) { if (this.editorText && this.editorText.setValue) { this.editorText.setValue(value) this.refresh() } } } } </script> <style lang="scss" > .dee-code-edit-com{ line-height: 15px } </style>