天天看點

Vue3 + TS + Vite 項目引入富文本框

最近開發新項目中使用到了富文本框,為了找一個簡潔好用的富文本還真是不容易,特此給自己記錄一下,也分享給大家!希望你需要的時候可以一步到位不用繞彎路。

網上常見的一些 tinymce-vue、quill、UEditor kindEditor ,國外的 CKEditor TinyMCE Quill ProseMirror Draft Slate 等等。我使用的是  ​

​wangeditor ​

​​

​編輯器。使用簡單,界面簡潔大氣,功能齊全,菜單工具欄可編輯,是一款非常強大的編輯器,是以我選擇了它。​

Vue3 + TS + Vite 項目引入富文本框

一、wangEditor 優勢

  1. 官方封裝了 Vue React 元件,可以很友善的​​用于 Vue React 等架構​​。支援 vue2 和 vue3 。
  2. wangEditor 有詳細的中文文檔,以及中文交流環境。因為​​作者open in new window​​就是國内程式員。
  3. 使用 vdom 技術(基于​​snabbdom.jsopen in new window​​ )做視圖更新,model 和 view 分離,增加穩定性。
  4. 可以支援 TypeScript。
  5. 官方中文文檔:https://www.wangeditor.com/v5/installation.html

二、針對 vue3 的安裝及使用

安裝:

yarn add @wangeditor/editor
# 或者 npm install @wangeditor/editor --save

yarn add @wangeditor/editor-for-vue@next
# 或者 npm install @wangeditor/editor-for-vue@next --save      

使用

<template>
    <div style="border: 1px solid #ccc">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      <Editor
        style="height: 500px; overflow-y: hidden;"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
      />
    </div>
</template>      
<script>import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

export default {
  components: { Editor, Toolbar },
  setup() {
    // 編輯器執行個體,必須用 shallowRef
    const editorRef = shallowRef()

    // 内容 HTML
    const valueHtml = ref('<p>hello</p>')

    // 模拟 ajax 異步擷取内容
    onMounted(() => {
        setTimeout(() => {
            valueHtml.value = '<p>模拟 Ajax 異步設定内容</p>'
        }, 1500)
    })

    const toolbarConfig = {}
    const editorConfig = { placeholder: '請輸入内容...' }

    // 元件銷毀時,也及時銷毀編輯器
    onBeforeUnmount(() => {
        const editor = editorRef.value
        if (editor == null) return
        editor.destroy()
    })

    const handleCreated = (editor) => {
      editorRef.value = editor // 記錄 editor 執行個體,重要!
    }

    return {
      editorRef,
      valueHtml,
      mode: 'default', // 或 'simple'
      toolbarConfig,
      editorConfig,
      handleCreated
    };
  }
}
</script>      

三、個性化配置

  • ​​工具欄配置​​ - 插入新菜單,屏蔽某個菜單等
  • ​​編輯器配置​​ - 兼聽各個生命周期,自定義粘貼
  • ​​菜單配置​​ - 配置顔色、字型、字号、連結校驗、上傳圖檔、視訊等

注意:配置項寫的時候有 JS 和 TS 兩種寫法,參考官方文檔配置:https://www.wangeditor.com/v5/toolbar-config.html。