前言:在 Vue 日常项目开发中,会遇到将后端传回的代码格式化输出渲染,并支持用户编辑的需求。实现方法有很多,可以分别使用 vue2-ace-editor  , vue-prism-editor ,codemirror


方法一:使用 vue2-ace-editor 插件实现

  • 安装
npm i vue2-ace-editor -S
// 或者
cnpm i vue2-ace-editor -S
  • 组件内使用实例
<template>
	<div class="codeEditBox">
		<editor v-model="code" @init="editorInit" @input='codeChange' lang="javascript" :options="editorOptions" theme="chrome"></editor>
	</div>
</template>

<script>
	import Editor from 'vue2-ace-editor'
	export default {
		name: 'CodeEditor',
		components: {
			Editor
		},
		data() {
			return {
                // 双向绑定的编辑器内容值属性
				code: 'console.log("Hello World");',
				editorOptions: {
					// 设置代码编辑器的样式
					enableBasicAutocompletion: true, //启用基本自动完成
					enableSnippets: true, // 启用代码段
					enableLiveAutocompletion: true, //启用实时自动完成
					tabSize: 2, //标签大小
					fontSize: 14, //设置字号
					showPrintMargin: false //去除编辑器里的竖线
				}
			}
		},
		methods: {
            // 编辑内容改变时触发
			codeChange(val) {
				val //console.log(val)
			},
			editorInit() {
				require('brace/theme/chrome')
				require('brace/ext/language_tools') //language extension prerequsite...
				require('brace/mode/yaml')
				require('brace/mode/json')
				require('brace/mode/less')
				require('brace/snippets/json')
				require('brace/mode/lua')
				require('brace/snippets/lua')
				require('brace/mode/javascript')
				require('brace/snippets/javascript')
			}
		}
	}
</script>

<style scoped>
	.codeEditBox {
		width: 100%;
		height: 200px;
	}
</style>

方法二:使用 vue-prism-editor 插件实现

  • 安装
npm i prismjs vue-prism-editor -S
// 或者
cnpm i prismjs vue-prism-editor
  • 组件内使用实例
<template>
	<div>
		<prism-editor class="my-editor height-300" v-model="code" :highlight="highlighter" :line-numbers="lineNumbers"></prism-editor>
	</div>
</template>

<script>
	import { PrismEditor } from 'vue-prism-editor'
	import 'vue-prism-editor/dist/prismeditor.min.css'
	import { highlight, languages } from 'prismjs/components/prism-core'
	import 'prismjs/components/prism-clike'
	import 'prismjs/components/prism-javascript'
	import 'prismjs/themes/prism-tomorrow.css'
	export default {
		name: 'CodeEditor1',
		components: {
			PrismEditor
		},
		data: () => ({
            // 双向绑定编辑器内容值属性
			code: 'console.log("Hello World");',
            // true为编辑模式, false只展示不可编辑
			lineNumbers: true 
		}),
		methods: {
			highlighter(code) {
				return highlight(code, languages.js) //returns html
			}
		}
	}
</script>

<style lang="css" scoped>
	/* required class */
	.my-editor {
		background: #2d2d2d;
		color: #ccc;
		font-family: Fira code, Fira Mono, Consolas, Menlo, Courier, monospace;
		font-size: 14px;
		line-height: 1.5;
		padding: 5px;
	}
	/* optional */
	.prism-editor__textarea:focus {
		outline: none;
	}
	/* not required: */
	.height-300 {
		height: 300px;
	}
</style>

方法三:使用 codemirror 插件实现

  • 安装
npm i codemirror -S
// 或者
npm i codemirror -S
  • 组件内使用实例
<template>
	<div class="in-coder-panel">
		<textarea ref="textarea"></textarea>
		<el-select class="code-mode-select" v-model="mode" @change="changeMode" size="mini">
			<el-option v-for="mode in modes" :key="mode.value" :label="mode.label" :value="mode.value"></el-option>
		</el-select>
	</div>
</template>

<script type="text/ecmascript-6">
	// 引入全局实例
	import _CodeMirror from 'codemirror'
	// 核心样式
	import 'codemirror/lib/codemirror.css'
	// 引入主题后还需要在 options 中指定主题才会生效
	import 'codemirror/theme/cobalt.css'
	// 需要引入具体的语法高亮库才会有对应的语法高亮效果
	// codemirror 官方其实支持通过 /addon/mode/loadmode.js 和 /mode/meta.js 来实现动态加载对应语法高亮库
	// 但 vue 貌似没有无法在实例初始化后再动态加载对应 JS ,所以此处才把对应的 JS 提前引入
	import 'codemirror/mode/javascript/javascript.js'
	import 'codemirror/mode/css/css.js'
	import 'codemirror/mode/xml/xml.js'
	import 'codemirror/mode/clike/clike.js'
	import 'codemirror/mode/markdown/markdown.js'
	import 'codemirror/mode/python/python.js'
	import 'codemirror/mode/r/r.js'
	import 'codemirror/mode/shell/shell.js'
	import 'codemirror/mode/sql/sql.js'
	import 'codemirror/mode/swift/swift.js'
	import 'codemirror/mode/vue/vue.js'
	// 尝试获取全局实例
	const CodeMirror = window.CodeMirror || _CodeMirror
	export default {
		name: 'CodeEditor2',
        // 父组件传给子组件
		props: {
			// 内容,用于实现双向绑定
			value: String,
			// 语法类型
			language: {
				type: String,
				default: null
			}
		},
		data() {
			return {
				// 双向绑定编辑器值属性
				code: '',
				// 默认的语法类型
				mode: 'javascript',
				// 编辑器实例
				coder: null,
				// 默认配置
				options: {
					// 缩进格式
					tabSize: 2,
					// 主题,对应主题库 JS 需要提前引入
					theme: 'cobalt',
					// 显示行号
					lineNumbers: true,
					line: true
				},
				// 支持切换的语法高亮类型,对应 JS 已经提前引入
				// 使用的是 MIME-TYPE ,不过作为前缀的 text/ 在后面指定时写死了
				modes: [
					{
						value: 'css',
						label: 'CSS'
					},
					{
						value: 'javascript',
						label: 'Javascript'
					},
					{
						value: 'html',
						label: 'XML/HTML'
					},
					{
						value: 'x-java',
						label: 'Java'
					},
					{
						value: 'x-objectivec',
						label: 'Objective-C'
					},
					{
						value: 'x-python',
						label: 'Python'
					},
					{
						value: 'x-rsrc',
						label: 'R'
					},
					{
						value: 'x-sh',
						label: 'Shell'
					},
					{
						value: 'x-sql',
						label: 'SQL'
					},
					{
						value: 'x-swift',
						label: 'Swift'
					},
					{
						value: 'x-vue',
						label: 'Vue'
					},
					{
						value: 'markdown',
						label: 'Markdown'
					}
				]
			}
		},
		mounted() {
			// 初始化
			this._initialize()
		},
		methods: {
			// 初始化
			_initialize() {
				// 初始化编辑器实例,传入需要被实例化的文本域对象和默认配置
				this.coder = CodeMirror.fromTextArea(this.$refs.textarea, this.options)
				// 编辑器赋值
				this.coder.setValue(this.value || this.code)
				// 支持双向绑定
				this.coder.on('change', (coder) => {
					this.code = coder.getValue()
					if (this.$emit) {
						this.$emit('input', this.code)
					}
				})
				// 尝试从父容器获取语法类型
				if (this.language) {
					// 获取具体的语法类型对象
					let modeObj = this._getLanguage(this.language)
					// 判断父容器传入的语法是否被支持
					if (modeObj) {
						this.mode = modeObj.label
					}
				}
			},
			// 获取当前语法类型
			_getLanguage(language) {
				// 在支持的语法类型列表中寻找传入的语法类型
				return this.modes.find((mode) => {
					// 所有的值都忽略大小写,方便比较
					let currentLanguage = language.toLowerCase()
					let currentLabel = mode.label.toLowerCase()
					let currentValue = mode.value.toLowerCase()
					// 由于真实值可能不规范,例如 java 的真实值是 x-java ,所以讲 value 和 label 同时和传入语法进行比较
					return (
						currentLabel === currentLanguage || currentValue === currentLanguage
					)
				})
			},
			// 更改模式
			changeMode(val) {
				// 修改编辑器的语法配置
				this.coder.setOption('mode', `text/${val}`)
				// 获取修改后的语法
				let label = this._getLanguage(val).label.toLowerCase()
				// 允许父容器通过以下函数监听当前的语法值
				this.$emit('language-change', label)
			}
		}
	}
</script>

<style lang="css" scoped>
	.in-coder-panel {
		position: relative;
	}
	.CodeMirror-code {
		line-height: 19px;
		text-align: left;
	}
	.code-mode-select {
		position: absolute;
		z-index: 2;
		right: 10px;
		top: 10px;
		max-width: 130px;
	}
</style>

完整代码示例:vue-code-editor: 在 VUE 中分别使用 vue2-ace-editor  , vue-prism-editor ,codemirror 等插件嵌入代码编辑器