前言
我们在项目中经常接触的富文本插件有很多应用方案,我常用的有quill-editor、tiptap、wangEditor。先简单介绍下区别:
- quill-editor:用的最多的插件,但是已经不在维护了。配置项很丰富,相反的是对新手就不那么友好了。
- tiptap:一个国外团队研发的框架,简单、强悍。由于文档是英文的且需要翻墙,所以需要自己想办法查阅。
- wangEditor:国产插件,母语文档。对新手来说比较友好,既然都要从头开始读文档,这个还相对容易一些。
安装
yarn add @wangeditor/editor
# 或者 npm install @wangeditor/editor --save
yarn add @wangeditor/editor-for-vue
# 或者 npm install @wangeditor/editor-for-vue --save
开始使用吧
1.在components封装组件
2.在组件内直接使用
<template>
<div style="border: 1px solid #ccc;">
<Toolbar
:defaultConfig="toolbarConfig"
:editor="editor"
:mode="mode"
style="border-bottom: 1px solid #ccc"
/>
<Editor
v-model="html"
:defaultConfig="editorConfig"
:mode="mode"
class="editor"
style="height: 500px; overflow-y: hidden;"
@onCreated="onCreated"
/>
</div>
</template>
<script>
import Vue from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
export default Vue.extend({
name: 'MyEditor',
components: { Editor, Toolbar },
data () {
return {
editor: null, // 编辑器实例
html: '<p>hello</p>', // 实例文本
toolbarConfig: {}, // 工具栏配置
editorConfig: { placeholder: '请输入内容...' },
mode: 'default' // or 'simple'
}
},
methods: {
onCreated (editor) {
this.editor = Object.seal(editor) // 一定要用 Object.seal() ,否则会报错
}
},
mounted () {
// 模拟 ajax 请求,异步渲染编辑器
setTimeout(() => {
this.html = '<p>模拟 Ajax 异步设置内容 HTML</p>'
}, 1500)
},
beforeDestroy () {
const editor = this.editor
if (editor == null) return
editor.destroy() // 组件销毁时,及时销毁编辑器
}
})
</script>
<!--引入css样式-->
<style src="@wangeditor/editor/dist/css/style.css"></style>
<!--根据项目UI需求配置自己的css-->
<style lang="scss">
.editor {
height: 200px !important;
#w-e-textarea-1 {
text-align: left !important;
}
.w-e-text-container {
text-align: left !important;
}
}
</style>
3.在需要用到组件的文件引入并注册
4.渲染到DOM结构就ok啦
详细配置稍后更新。。。