vue 实现富文本
vue 实现富文本的方法
在 Vue 中实现富文本功能通常需要借助第三方库或组件。以下是几种常见的实现方式:
使用 vue-quill-editor
vue-quill-editor 是基于 Quill 的 Vue 富文本编辑器组件,安装简单且功能强大。
安装依赖:
npm install vue-quill-editor quill
基本使用示例:
<template>
<quill-editor v-model="content" />
</template>
<script>
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.snow.css'
export default {
components: { quillEditor },
data() {
return {
content: ''
}
}
}
</script>
使用 tinymce-vue
TinyMCE 是专业级的富文本编辑器,tinymce-vue 是其官方 Vue 封装。
安装依赖:
npm install @tinymce/tinymce-vue tinymce
基本使用示例:

<template>
<editor
v-model="content"
api-key="your-api-key"
:init="editorConfig"
/>
</template>
<script>
import Editor from '@tinymce/tinymce-vue'
export default {
components: { Editor },
data() {
return {
content: '',
editorConfig: {
height: 500,
plugins: 'link image code',
toolbar: 'undo redo | bold italic | alignleft aligncenter alignright | code'
}
}
}
}
</script>
使用 wangEditor
wangEditor 是轻量级的富文本编辑器,对中文支持良好。
安装依赖:
npm install wangeditor
基本使用示例:
<template>
<div ref="editor" style="text-align:left"></div>
</template>
<script>
import E from 'wangeditor'
export default {
data() {
return {
editor: null,
content: ''
}
},
mounted() {
this.editor = new E(this.$refs.editor)
this.editor.config.onchange = (html) => {
this.content = html
}
this.editor.create()
},
beforeDestroy() {
this.editor.destroy()
this.editor = null
}
}
</script>
使用 CKEditor 5
CKEditor 5 提供了现代化的富文本编辑体验。

安装依赖:
npm install @ckeditor/ckeditor5-vue @ckeditor/ckeditor5-build-classic
基本使用示例:
<template>
<ckeditor :editor="editor" v-model="content" />
</template>
<script>
import CKEditor from '@ckeditor/ckeditor5-vue'
import ClassicEditor from '@ckeditor/ckeditor5-build-classic'
export default {
components: { ckeditor: CKEditor.component },
data() {
return {
editor: ClassicEditor,
content: ''
}
}
}
</script>
富文本内容的安全处理
使用富文本编辑器时,需要注意 XSS 攻击防护。可以使用 DOMPurify 等库对内容进行净化:
npm install dompurify
使用示例:
import DOMPurify from 'dompurify'
const cleanHtml = DOMPurify.sanitize(dirtyHtml)
自定义富文本功能
对于特定需求,可能需要扩展或自定义富文本功能。大多数编辑器都支持插件扩展和自定义配置,具体方法可参考各编辑器的官方文档。
性能优化建议
对于频繁更新的富文本内容,可以使用 debounce 技术减少不必要的渲染和保存操作。同时,对于大型文档,考虑使用懒加载或分块处理技术。






