效果預覽:
前言
不算實習,前端從業已經兩年了。負責或參與過的平台/項目數量已經有十幾個了,這些項目當中,多多少少都需要用到編輯器。
簡單的后台form表單中,一個textarea就已經夠用,稍微麻煩點的,比如需要能粘進來元素樣式的,設置一下元素的 contenteditable="true"也能滿足需求。
但是有些項目,比如知識管理(文章編輯)、埋點平台(編輯發送總結郵件)這種,就需要專業的富文本編輯器來進行一定定制來滿足需要。
那么,我們要如何選擇一個合適的富文本編輯器呢?
眾所周知,富文本編輯器有所見即所得的特性,展示實際上需要html源碼。
就我自己就用過:
ueditor:百度 fex 的
市面上開源的還有:
editor.js
wangeditor
TinyMCE
kindeditor
simditor
Quill
slatejs
prosemirror
真讓人眼花繚亂,不過支持 Vue,自帶功能足夠全面(表格、圖片等),支持寫插件擴展,很方便就能協同編輯的就只有tiptap了。
tiptap基於prosemirror,用過tiptap V1 的我對其穩定性和豐富的api印象很深刻。
而tiptap V2 則大量改寫了 V1 的 api,升級需要花費很多功夫,v1的插件很多都沒辦法在v2上繼續用了,就需要逐一升級一下。
v2也解決了v1很多bug,比如v1,checklist和orderlist或者unorderlist互轉就不支持,v2上就解決了這個問題。
另外v2對於多人協同編輯的支持程度也更高,圍繞多人編輯有
新建組件項目
1 npm i @tiptap/vue-2 @tiptap/starter-kit @tiptap/extension-task-list @tiptap/extension-task-item @tiptap/extension-highlight @tiptap/extension-character-count
基於 vue 2 就使用 @tiptap/vue-2 這個依賴,starter-kit 則是包含了很多基本功能,比如 text、bold、italic、header、history 等等插件。
再裝一下element-ui組件庫。
npm i element-ui
因為我們要用組件庫來定制裝修編輯器。
接下來在我們創建好的組件倉庫的入口vue文件中引入tiptap v2 的套件,並做初始化。
並且應用vue的響應式特性,對數據做一定監聽處理。再設計下props,外部引用組件的時候就可以通過v-model雙向綁定了。
<template>
<div
class="editor"
v-if="editor">
<editor-content class="editor__content" :editor="editor" />
</div>
</template>
<script>
import StarterKit from '@tiptap/starter-kit';
import { Editor, EditorContent } from '@tiptap/vue-2';
export default {
name: 'dudu-editor',
components: {
EditorContent
},
props: {
value: {
type: String,
default: ''
}
},
data() {
return {
editor: null
};
},
watch: {
value(v) {
const isSame = this.value === v;
if (isSame) return;
this.editor.commands.setContent(this.value, false);
}
},
mounted() {
this.editor = new Editor({
content: this.value,
extensions: [
StarterKit
],
onUpdate: () => {
// HTML
this.$emit('input', this.editor.getHTML());
// JSON
// this.$emit('input', this.editor.getJSON())
}
});
},
beforeDestroy() {
this.editor.destroy();
}
};
</script>
通過vue.use全局注冊之后,接下來,在外部組件就可以使用我們的編輯器了。
<template>
<div class="main">
<div>dudu-editor 嘟嘟富文本編輯器</div>
<dudu-editor v-model="value">222</dudu-editor>
<div>渲染展示</div>
<div class="output ProseMirror" v-html="value"></div>
</div>
</template>
<script>
import './index.scss';
export default {
name: 'demo',
components: {
},
data() {
return {
value: ''
};
}
};
</script>
<style lang="scss" scoped>
@import '../components/main.scss';
.space {
height: 100px;
}
.output {
padding: 10px;
}
</style>

