本篇文章同步發表於 2023 iThome 鐵人賽:Nuxt.js 3.x 筆記-打造 SSR 專案
CKEditor 版本:v39.0.0
Nuxt2 搭配 CKEditor 5 請參考 這篇文章
CKEditor 是一套歷史悠久且功能完整、輕量的富文本編輯器(rich text editor),為使用者提供所見即所得(WYSIWYG)的編輯區域。與舊版不同,CKEditor 5 使用 MVC 架構、ES6 編寫、UI 簡潔,且因應現在的前後端分離趨勢,與前端框架 React、Angular、and Vue.js 做整合,讓我們可以更便利的開發應用。
接下來說明如何在 Nuxt3 + Vite 環境搭配 CKEditor 開發,分別介紹以下兩種安裝方式:
1. 使用預先定義的組合
2. 自行配置功能
注意: CKEditor 只能在 client 端運作,否則會拋
self is not defined
錯誤
提供兩個解法:
- 設定為
ssr: false
,關閉 server 端渲染- 將 CKEditor 元件包在自訂元件內,檔名加上
.client
後綴,限制元件在 client 端運作。EX:components/TheCkeditor.client.vue
1. 使用預先定義的組合
提供以下幾種組合,各組合功能可以參考 官方文件
- Classic editor
- Inline editor
- Balloon editor
- Balloon block editor
- Document editor
- Multi-root editor
- Superbuild
以 Classic editor 進行說明:
套件安裝
|
使用元件與組合功能
ckeditor components:
- editor:定義編輯器使用的組件
- v-model:資料雙向綁定
- config:定義設定檔
|
@ckeditor/ckeditor5-build-classic
將相關功能包裝成組件,使用方式非常簡單,但無法另外擴充功能,因 @ckeditor/ckeditor5-build-classic
已將相依套件安裝進去,重複安裝會拋錯誤:
CKEditorError: ckeditor-duplicated-modules
CKEditor 在初始化時因模組重複執行導致錯誤,需改用以下「自行配置功能」
2. 自行配置功能
選擇專案需要的功能,可以彈性的客製化組合文字編輯器
注意:所有 ckeditor 套件版本必須相同(除了
@ckeditor/ckeditor5-dev-*
、@ckeditor/ckeditor5-vue
跟@ckeditor/vite-plugin-ckeditor5
)
套件安裝
- 安裝 Vue / Vite 整合套件
|
- 安裝預設主題樣式
|
自選功能(功能眾多不一一說明)
以下舉例:
@ckeditor/ckeditor5-editor-classic
:toolbar style@ckeditor/ckeditor5-paragraph
:paragraph style@ckeditor/ckeditor5-essentials
:selectAll、undo、redo …@ckeditor/ckeditor5-font
:fontSize、fontFamily、fontColor、fontBackgroundColor@ckeditor/ckeditor5-basic-styles
:bold、italic、underline、strikethrough、code …@ckeditor/ckeditor5-link
:link、linkImage
|
nuxt.config 配置
|
使用元件與自選功能
ckeditor components:
- editor:定義編輯器使用的組件
- v-model:資料雙向綁定
- config:定義設定檔
- placeholder:編輯器佔位符
- plugins:使用插件
- toolbar:配置工具列,可以加插入分隔符號
|
|
畫面呈現如下:
自訂 CSS 樣式
前面提到透過 @ckeditor/ckeditor5-theme-lark
定義了預設樣式,如果想依照專案需求調整配色,只要修改 CKEditor 的 CSS 自訂變數即可:
|
調整後畫面:
參考資源:
https://ckeditor.com/docs/ckeditor5/latest/installation/integrations/vuejs-v3.html
https://ckeditor.com/docs/ckeditor5/latest/installation/advanced/alternative-setups/integrating-from-source-vite.html
https://ckeditor.com/docs/ckeditor5/latest/framework/deep-dive/ui/theme-customization.html
評論