一文完全掌握富文本编辑器TinyMCE

一、安装和引入

TinyMCE 是主流富文本编辑器,功能非常全,你需要的大多数功能它都支持,类似在线版的 Word。但它的优势也恰恰是它的劣势,如此之多的功能都放上来导致整个编辑器非常重,如果只是需要简单功能,上这么复杂的编辑器,大材小用。

TinyMCE 对 Vue.js 的集成和安装非常友好,支持 Vue3 和 TypeScript,文档写的也非常好。

TinyMCE-Vue文档
TinyMCE 6 原生文档

1. 安装

npm install --save "@tinymce/tinymce-vue@^5"

2. 引入

<script setup>
import {ref} from 'vue'
import Editor from '@tinymce/tinymce-vue'

const setting=ref({
  xxx
})
const content=ref('')
</script>

<template>
<Editor
    api-key="xxx"
    :init="setting"
    v-model="content"
/>
</template>

其中,api-key需要到https://www.tiny.cloud/my-account/integrate注册并获取,否则编辑器是只读状态。

3. 三种模式

TinyMCE有三种模式:经典模式(classic)、内联模式(inline)、简洁模式(distraction-free)。

经典模式是默认模式,其在页面内嵌入iframe,编辑器里的内容和样式处于沙箱中,不会收到页面其它内容的影响。

内联模式需要初始化时配置 inline: true,内联区域未激活时,编辑器处于隐藏状态,当内联区域被激活时,编辑器工具栏才会显示。这种特性可用于所见即所得的页面编辑,且编辑器内容可受到页面其它区域的样式和脚本的影响。注意,内联模式在移动设备下无效。

简洁模式是基于内联模式,通过插件quickbars增强了交互性,要启用简洁模式,可在初始化时配置:plugins:['quickbars'], toolbar: false, menubar: false, inline: true

4. 手机端应用

为了使手机端编辑器正确表现,需要在页面head段添加元信息:<meta name="viewport" content="width=device-width, initial-scale=1">

注意,有些功能在手机端并不支持,比如inline、toolbar_sticky、table_grid、resize、object_resizing等。

二、初始化参数

1. 基本参数

// 尺寸
max_height:800,
min_height:400,
width: '100%'

menubar: true, // 设置富文本编辑器菜单, 默认true
branding: false, // 关闭底部官网提示 默认true
statusbar: true, // 显示底部状态栏 默认true
readonly: false, // 设置只读属性 默认 false
resize: true, // 调节编辑器大小 默认 true
placeholder: '请输入内容', // 占位符

theme:'silver',
skin:'oxide',
content_style: 'body, p{font-size: medium;}', // 为内容区编辑自定义css样式
language_url: '/tinymce/langs/zh_CN.js', // 中文化 默认为英文
language: 'zh_CN', // 设置富文本编辑器语言

关于语言和皮肤:

在项目public目录下新建tinymce目录,在该目录下分别新建langs和skins目录,用于存放语言包和皮肤包。

语言包下载地址为:https://www.tiny.cloud/get-tiny/language-packages/。文件下载后放入/public/tinymce/langs目录下,并配置 language_url:"/tinymce/langs/zh_CN.js", language:"zh_CN"

皮肤默认为oxide,我们可以通过官网提供的皮肤定制功能自定义皮肤:https://skin.tiny.cloud/t5/。将自定义的皮肤文件(CUSTOM)下载后,解压到/public/tinymce/skins目录下,并配置 skin:'CUSTOM', skin_url:'/tinymce/skins/CUSTOM/skins/ui'

2. toolbar配置

(1) toolbar基本配置:

toolbar:'undo redo styles bold italic | link image',
toolbar_mode: 'warp',	//超出宽度的展示方式
toolbar_sticky: true	//超出高度的跟随方式

toolbar可使用字符串或数组形式。使用字符串形式时,通过 | 分组,当超出页面宽度后,分组内容会折叠,折叠模式可通过toolbar_mode参数进行配置。也可设置为false关闭toolbar。

toolbar_mode有四种模式:floating、sliding、scrolling和wrap。floating将以悬浮模式弹出折叠内容,sliding将把折叠内容展出到工具栏下方,scrolling将使工具栏左右可滚动,wrap与sliding布局相同,但默认展开。

toolbar_sticky设置窗口向下滚动时工具栏是否跟随滚动。

(2) 常用toolbar按钮

名字描述
aligncenterCenter aligns the current block or image.
alignjustifyFull aligns the current block or image.
alignleftLeft aligns the current block or image.
alignnoneRemoves the alignment of the current block or image.
alignrightRight aligns the current block or image.
blockquoteApplies block quote format to the current block level element.
backcolorApplies background color to selection.
blocksDropdown list with block formats to apply to selection.
boldApplies the bold format to the current selection.
copyCopies the current selection into clipboard.
cutCuts the current selection into clipboard.
fontfamilyDropdown list with font families to apply to selection.
fontsizeDropdown list with font sizes to apply to selection.``The fontsize and fontsizeinput toolbar buttons should not be placed in a toolbar group together or otherwise presented together.
fontsizeinputText entry input field to change font size of selection or current insertion point. Also provides increase and decrease font size buttons on either side of said input field.This toolbar button is commonly used in conjunction with the `<a href="https://www.tiny.cloud/docs/tinymce/6/user-formatting-options/#font_size_input_default_unit" class="xref page">font_size_input_default</a>` configuration option.The fontsize and fontsizeinput toolbar buttons should not be placed in a toolbar group together or otherwise presented together.
forecolorApplies foreground/text color to selection.
h1Changes current line to the “Heading 1” style.
h2Changes current line to the “Heading 2” style.
h3Changes current line to the “Heading 3” style.
h4Changes current line to the “Heading 4” style.
h5Changes current line to the “Heading 5” style.
h6Changes current line to the “Heading 6” style.
hrInserts a horizontal rule into the editor.
indentIndents the current list item or block element.
italicApplies the italic format to the current selection.
languageDropdown list with languages to apply to the selection. This button requires thecontent_langs option.
lineheightDropdown list with line heights to apply to selection.
newdocumentCreates a new document.
outdentOutdents the current list item or block element.
pastePastes the current clipboard into the editor.
pastetextToggles plain text pasting mode on/off. When in plain text mode, all rich content is converted into plain text.
printPrints the current editor contents.
redoTo redo the last undone operation.
removeRemoves (deletes) the selected content or the content before the cursor position.
removeformatRemoves the formatting from the current selection.
selectallSelects all content in the editor.
strikethroughApplies strike though format to the current selection.
stylesDropdown list with styles to apply to selection.
subscriptApplies subscript format to the current selection.
superscriptApplies superscript format to the current selection.
underlineApplies the underline format to the current selection.
undoTo undo the last operation.
visualaidToggles the visual aids for invisible elements.

3. plugin配置

(1) advlist

高级列表,依赖于lists插件。

plugins:'lists advlist'
toolbar:'bullist numlist'

bullist提供不同样式是列表(圆形、方形等),numlist提供数字开头列表(可以为数字、字母、罗马字母等)

(2) anchor

锚点,可配合link插件,在插入url时选择设定的锚点,实现页内跳转。

plugins:'anchor',
toolbar:'anchor'

(3) autolink

自动将url地址转化为link。

plugins:'autolink'

(4) autoresize

随着用户输入内容的增多,自动调整编辑器高度。若设定了max_height,当编辑器高度达到设定值时,将停止自动调整。

plugins:'autoresize'

(5) autosave

根据设定时间间隔自动保存内容,以及在离开页面时询问是否保存内容。

plugins:'autosave',
toolbar: 'restoredraft',
autosave_interval: '20s', //自动保存的时间间隔

(6) code

插入和编辑文档的html源码。

plugins:'code',
toolbar:'code'

(7) codesample

插入代码块,可渲染html、js、c、JAVA、PHP、Python等多种类型代码。

plugins:'codesample',
toolbar:'codesample'

(8) emoticons

插入表情。

plugins:'emoticons',
toolbar:'emoticons'

(9) fullscreen

全屏。

plugins:'fullscreen',
toolbar:'fullscreen'

(10) image

插入图片。

上传本地图片有两种配置方法:一种是使用image插件提供的image_uploadtab,需要同时配置image_upload_url;另一种是配置file_picker_callback,针对link、media和image三种类型的文件,可统一使用file_picker_callback进行处理。

示例中是使用image_uploadtab配置本地上传图片。本文第三节将介绍如何配置file_picker_callback分别上传文件、多媒体和图片,该方式是本人推荐的文件上传方式。

plugins:'image',
toolbar:'image',
image_uploadtab:true,                             //允许从本地上传图片,需要同时配置images_upload_url
images_upload_url:'/api/information/upload_img',  //配置后台接受和存储图片的url
automatic_uploads:true,                           //开启自动上传,可以不用配置image_upload_handler,上传图片将包含在报文files段,名字为file。
// images_upload_handler:handleUploadImg,         //手工上传函数,见下。
image_prepend_url:'/minio/information/',          //图片上传后的url前缀
paste_data_images: true,                          //可以直接拖动图片或粘贴图片到编辑区。
images_file_types:'jpeg,jpg,png'                  //默认值为'jpeg,jpg,jpe,jfi,jif,jfif,png,gif,bmp,webp'
//手工配置images_upload_handler:handleUploadImg,则使用该回调函数上传图片。回调函数返回一个Promise对象,上传成功则返回Promise.resolve('图片url')。
//若返回的图片名,可配合image_prepend_url配置项设定图片的url前缀。
async function handleUploadImg(blobInfo, progress){
    let formData=new FormData()
    formData.append('file',blobInfo.blob(), 'img.png')
    // 上传头像
    var ret=await axios.post(
        `/api/information/upload_img`,
        formData,
        {headers:{'Content-Type':'multipart/form-data'}}
    )
    return ret.data.location
}

(11) link

插入超链接。若配置file_picker_callback,则可以上传本地文件,具体方式见第三节。

plugins:'link',
toolbar:'link'

(12) lists

插入多种类型的列表。

plugins:'lists',
toolbar:'numlist bullist'   //数字、字母、希腊字母开头的列表和圆圈、圆点、方块开头的列表

(13) media

插入多媒体文件。若配置file_picker_callback,则可以上传本地文件,具体方式见第三节。

plugins:'media',
toolbar:'media'

(14) preview

预览。

plugins:'preview',
toolbar:'preview'

(15) save

保存文件。

plugins:'save',
toolbar:'save',
save_onsavecallback:()=>{
  //执行axios上传,保存文件。
  ...
}

(16) searchreplace

查找和替换。

plugins:'searchreplace',
toolbar:'searchreplace'

(17) table

表格。

plugins:'table',
toolbar:'table'

(18) wordcount

在状态栏显示单词数。

plugins:'wordcount',
toolbar:'wordcount'

4. menu配置

若使用toolbox,可关闭menu。

menubar:false

也可通过类似配置toolbox的方式配置menu:

menubar:'file edit insert view format table tools help'

三、上传文件

通过配置file_picker_callback,可以在link、image、media插件显示上传本地文件按钮。

file_picker_callback:handleUploadFile,
file_picker_types:'file image media',    //默认三种类型,分别对应link、image和media组件的上传

回调函数有三个参数(callback, value, meta)。

callback是一个函数,用于返回上传文件的url。

value没有用。

meta提供组件类别信息,通过meta.filetype可以判断回调来自于link、image还是media组件。

function handleUploadFile(callback, value, meta){
    var input=document.createElement('input')
    input.setAttribute('type','file')
    var accept_filetypes=''
    switch(meta.filetype){  //判断回调来自于哪个组件,并为不同组件设置文件后缀过滤。
        case 'file':
            accept_filetypes='.doc,.docx,.ppt,.pptx,.xls,.xlsx,.pdf,.txt' 
            break
        case 'image':
            accept_filetypes='.webp,.png,.jpg,.jpeg,.gif,.svg'
            break
        case 'media':
            accept_filetypes='.weba,.wav,.mp3,.webm,.mpg,.mpeg,.avi,.wmv'
            break
    }
    input.setAttribute('accept',accept_filetypes) //设置文件选择框的文件过滤选项。
    input.click() //打开文件选择框
    input.onchange=async ()=>{ //选中文件点击确认后,执行上传操作
        var file=input.files[0]
        let formData=new FormData()
        formData.append('content_type',file.type)
        formData.append('file', file, file.name)
        var ret=await axios.post(
            '/api/information/upload',
            formData,
            {headers:{'Content-Type':'multipart/form-data'}}
        )
        callback('/minio/information/'+ret.data.name)
    }
}
Vue 3中有很多富文本编辑器的选择,其中一个常用的是TinyMCE。要在Vue 3中使用TinyMCE富文本编辑器,可以按照以下步骤进行: 1. 首先,使用npm或者yarn安装TinyMCE编辑器依赖包: ``` npm install tinymce ``` 2. 在Vue组件中引入需要的TinyMCE编辑器资源文件。有多种方式可以引入,这里以CDN引入为例: ```html <script src="https://cdn.jsdelivr.net/npm/tinymce@5"></script> ``` 3. 创建一个Vue组件,并在其中添加一个textarea元素作为编辑器容器: ```html <template> <div> <textarea id="my-editor"></textarea> </div> </template> ``` 4. 在Vue组件的`mounted`钩子函数中初始化TinyMCE编辑器,并指定其选项和回调函数: ```javascript <script> import { onMounted } from 'vue'; export default { mounted() { onMounted(() => { tinymce.init({ selector: '#my-editor', height: 500, plugins: 'advlist autolink lists link image charmap print preview anchor', toolbar: 'undo redo | formatselect | bold italic backcolor | \ alignleft aligncenter alignright alignjustify | \ bullist numlist outdent indent | removeformat | help', setup: (editor) => { editor.on('change', () => { this.$emit('input', editor.getContent()); }); }, }); }); }, }; </script> ``` 这里的选项和回调函数可以根据实际需要进行配置,你可以根据TinyMCE的文档来设置更多的选项。 5. 最后,在使用该组件的父组件中,可以通过`v-model`来双向绑定富文本编辑器的内容: ```html <template> <div> <RichTextEditor v-model="content" /> <div> <h3>输出的内容:</h3> <div v-html="content"></div> </div> </div> </template> <script> import RichTextEditor from './RichTextEditor.vue'; export default { components: { RichTextEditor, }, data() { return { content: '', }; }, }; </script> ``` 这样,就可以在Vue 3中使用TinyMCE富文本编辑器了。希望对你有所帮助!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值