初始化
因为tinymce的Plugins
是按需加载的
为了能先快速上手这个编辑器
就先在vue-cli的 index.html 中默认塞入一条在线 cdn 地址,cdn 有时候会抽风可以下载代码到项目根目录
<script src="https://cdn.bootcss.com/tinymce/4.7.4/tinymce.min.js"></script>
记得去下载语言包到本地,
然后就在文件内引入,语言包可以不用引入,放在根目录 static/tinymce/langs 文件夹内,初始化会自动加载
import './zh_CN.js'
后面有机会再写下单独打包的事项,毕竟这货体积还不小。
插入 vue 组件模板
<template>
<div>
<textarea :id= "Id" ref="tinymce"></textarea>
</div>
</template>
记得一定要在textarea
外面包一层 div,不然…你自己试试看就知道了。
如果一个页面可能同时出现多个tinymce编辑器可以用vue中 ref 选择 dom 节点,如:this.$refs.tinymce
组件基础配置
将 tinymce 通过指定的 selector 挂载到组件中
<template>
<div>
<textarea :id= "Id"></textarea>
</div>
</template>
<script>
import './zh_CN.js'
export default {
data () {
const Id = Date.now()
return {
Id: Id,
Editor: null,
DefaultConfig: {}
}
},
props: {
value: {
default: '',
type: String
},
config: {
type: Object,
default: () => {
return {
theme: 'modern',
height: 300
}
}
}
},
mounted () {
this.init()
},
beforeDestroy () {
// 销毁 tinymce
this.$emit('on-destroy')
window.tinymce.remove(`#${this.Id}`)
},
methods: {
init () {
const self = this
this.Editor = window.tinymce.init({
// 默认配置
...this.DefaultConfig,
// prop 内传入的的 config
...this.config,
// 挂载的 DOM 对象
selector: `#${this.Id}`,
setup: (editor) => {
// 抛出 'on-ready' 事件钩子
editor.on(
'init', () => {
self.loading = false
self.$emit('on-ready')
editor.setContent(self.value)
}
)
// 抛出 'input' 事件钩子,同步 value 数据
editor.on(
'input change undo redo', () => {
self.$emit('input', editor.getContent())
}
)
}
})
}
}
}
</script>
好了,组件基本的初始化完成,后面正式开始踩坑之旅
API
具体内容看官网的 API就行,英语不好的用 chrome 翻译下对照着 demo 也能看个七七八八,当然主要原因还是我比较懒。
我这边根据自身业务需求在组件的data
内写了个默认配置
DefaultConfig: {
// GLOBAL
height: 500,
theme: 'modern',
menubar: false,
toolbar: `styleselect | fontselect | formatselect | fontsizeselect | forecolor backcolor | bold italic underline strikethrough | image media | table | alignleft aligncenter alignright alignjustify | outdent indent | numlist bullist | preview removeformat hr | paste code link | undo redo | fullscreen `,
plugins: `
paste
importcss
image
code
table
advlist
fullscreen
link
media
lists
textcolor
colorpicker
hr
preview
`,
// CONFIG
forced_root_block: 'p',
force_p_newlines: true,
importcss_append: true,
// CONFIG: ContentStyle 这块很重要, 在最后呈现的页面也要写入这个基本样式保证前后一致, `table`和`img`的问题基本就靠这个来填坑了
content_style: `
* { padding:0; margin:0; }
html, body { height:100%; }
img { max-width:100%; display:block;height:auto; }
a { text-decoration: none; }
iframe { width: 100%; }
p { line-height:1.6; margin: 0px; }
table { word-wrap:break-word; word-break:break-all; max-width:100%; border:none; border-color:#999; }
.mce-object-iframe { width:100%; box-sizing:border-box; margin:0; padding:0; }
ul,ol { list-style-position:inside; }
`,
insert_button_items: 'image link | inserttable',
// CONFIG: Paste
paste_retain_style_properties: 'all',
paste_word_valid_elements: '*[*]', // word 需要它
paste_data_images: true, // 粘贴的同时能把内容里的图片自动上传,非常强力的功能
paste_convert_word_fake_lists: false, // 插入 word 文档需要该属性
paste_webkit_styles: 'all',
paste_merge_formats: true,
nonbreaking_force_tab: false,
paste_auto_cleanup_on_paste: false,
// CONFIG: Font
fontsize_formats: '10px 11px 12px 14px 16px 18px 20px 24px',
// CONFIG: StyleSelect
style_formats: [
{
title: '首行缩进',
block: 'p',
styles: { 'text-indent': '2em' }
},
{
title: '行高',
items: [
{title: '1', styles: { 'line-height': '1' }, inline: 'span'},
{title: '1.5', styles: { 'line-height': '1.5' }, inline: 'span'},
{title: '2', styles: { 'line-height': '2' }, inline: 'span'},
{title: '2.5', styles: { 'line-height': '2.5' }, inline: 'span'},
{title: '3', styles: { 'line-height': '3' }, inline: 'span'}
]
}
],
// FontSelect
font_formats: `
微软雅黑=微软雅黑;
宋体=宋体;
黑体=黑体;
仿宋=仿宋;
楷体=楷体;
隶书=隶书;
幼圆=幼圆;
Andale Mono=andale mono,times;
Arial=arial, helvetica,
sans-serif;
Arial Black=arial black, avant garde;
Book Antiqua=book antiqua,palatino;
Comic Sans MS=comic sans ms,sans-serif;
Courier New=courier new,courier;
Georgia=georgia,palatino;
Helvetica=helvetica;
Impact=impact,chicago;
Symbol=symbol;
Tahoma=tahoma,arial,helvetica,sans-serif;
Terminal=terminal,monaco;
Times New Roman=times new roman,times;
Trebuchet MS=trebuchet ms,geneva;
Verdana=verdana,geneva;
Webdings=webdings;
Wingdings=wingdings,zapf dingbats`,
// Tab
tabfocus_elements: ':prev,:next',
object_resizing: true,
// Image
imagetools_toolbar: 'rotateleft rotateright | flipv fliph | editimage imageoptions'
}
因为本人比较懒,以上配置导出的代码可能会有代码注入的风险,建议保存的时候再前后端都做下注入过滤,不过一般数据安全问题主要还是服务器那边的事情?。
后面的图片上传可以单独拆出来做个小配置,直接写到props
里好了。
url: {
default: '',
type: String
},
accept: {
default: 'image/jpeg, image/png',
type: String
},
maxSize: {
default: 2097152,
type: Number
},
withCredentials: {
default: false,
type: Boolean
}
然后把这套东西塞到init
配置里
// 图片上传
images_upload_handler: function (blobInfo, success, failure) {
if (blobInfo.blob().size > self.maxSize) {
failure('文件体积过大')
}
if (self.accept.indexOf(blobInfo.blob().type) >= 0) {
uploadPic()
} else {
failure('图片格式错误')
}
function uploadPic () {
const xhr = new XMLHttpRequest()
const formData = new FormData()
xhr.withCredentials = self.withCredentials
xhr.open('POST', self.url)
xhr.onload = function () {
if (xhr.status !== 200) {
// 抛出 'on-upload-fail' 钩子
self.$emit('on-upload-fail')
failure('上传失败: ' + xhr.status)
return
}
const json = JSON.parse(xhr.responseText)
// 抛出 'on-upload-success' 钩子
self.$emit('on-upload-complete' , [
json, success, failure
])
}
formData.append('file', blobInfo.blob())
xhr.send(formData)
}
}
至此, 一个组件的封装基本算是完成了
看下初阶成果
<template>
<div>
<textarea :id= "Id"></textarea>
</div>
</template>
<script>
import './zh_CN.js'
export default {
data () {
const Id = Date.now()
return {
Id: Id,
Editor: null,
DefaultConfig: {
// GLOBAL
height: 500,
theme: 'modern',
menubar: false,
toolbar: `styleselect | fontselect | formatselect | fontsizeselect | forecolor backcolor | bold italic underline strikethrough | image media | table | alignleft aligncenter alignright alignjustify | outdent indent | numlist bullist | preview removeformat hr | paste code link | undo redo | fullscreen `,
plugins: `
paste
importcss
image
code
table
advlist
fullscreen
link
media
lists
textcolor
colorpicker
hr
preview
`,
// CONFIG
forced_root_block: 'p',
force_p_newlines: true,
importcss_append: true,
// CONFIG: ContentStyle 这块很重要, 在最后呈现的页面也要写入这个基本样式保证前后一致, `table`和`img`的问题基本就靠这个来填坑了
content_style: `
* { padding:0; margin:0; }
html, body { height:100%; }
img { max-width:100%; display:block;height:auto; }
a { text-decoration: none; }
iframe { width: 100%; }
p { line-height:1.6; margin: 0px; }
table { word-wrap:break-word; word-break:break-all; max-width:100%; border:none; border-color:#999; }
.mce-object-iframe { width:100%; box-sizing:border-box; margin:0; padding:0; }
ul,ol { list-style-position:inside; }
`,
insert_button_items: 'image link | inserttable',
// CONFIG: Paste
paste_retain_style_properties: 'all',
paste_word_valid_elements: '*[*]', // word 需要它
paste_data_images: true, // 粘贴的同时能把内容里的图片自动上传,非常强力的功能
paste_convert_word_fake_lists: false, // 插入 word 文档需要该属性
paste_webkit_styles: 'all',
paste_merge_formats: true,
nonbreaking_force_tab: false,
paste_auto_cleanup_on_paste: false,
// CONFIG: Font
fontsize_formats: '10px 11px 12px 14px 16px 18px 20px 24px',
// CONFIG: StyleSelect
style_formats: [
{
title: '首行缩进',
block: 'p',
styles: { 'text-indent': '2em' }
},
{
title: '行高',
items: [
{title: '1', styles: { 'line-height': '1' }, inline: 'span'},
{title: '1.5', styles: { 'line-height': '1.5' }, inline: 'span'},
{title: '2', styles: { 'line-height': '2' }, inline: 'span'},
{title: '2.5', styles: { 'line-height': '2.5' }, inline: 'span'},
{title: '3', styles: { 'line-height': '3' }, inline: 'span'}
]
}
],
// FontSelect
font_formats: `
微软雅黑=微软雅黑;
宋体=宋体;
黑体=黑体;
仿宋=仿宋;
楷体=楷体;
隶书=隶书;
幼圆=幼圆;
Andale Mono=andale mono,times;
Arial=arial, helvetica,
sans-serif;
Arial Black=arial black, avant garde;
Book Antiqua=book antiqua,palatino;
Comic Sans MS=comic sans ms,sans-serif;
Courier New=courier new,courier;
Georgia=georgia,palatino;
Helvetica=helvetica;
Impact=impact,chicago;
Symbol=symbol;
Tahoma=tahoma,arial,helvetica,sans-serif;
Terminal=terminal,monaco;
Times New Roman=times new roman,times;
Trebuchet MS=trebuchet ms,geneva;
Verdana=verdana,geneva;
Webdings=webdings;
Wingdings=wingdings,zapf dingbats`,
// Tab
tabfocus_elements: ':prev,:next',
object_resizing: true,
// Image
imagetools_toolbar: 'rotateleft rotateright | flipv fliph | editimage imageoptions'
}
}
},
props: {
value: {
default: '',
type: String
},
config: {
type: Object,
default: () => {
return {
theme: 'modern',
height: 300
}
}
},
url: {
default: '',
type: String
},
accept: {
default: 'image/jpeg, image/png',
type: String
},
maxSize: {
default: 2097152,
type: Number
},
withCredentials: {
default: false,
type: Boolean
}
},
mounted () {
this.init()
},
beforeDestroy () {
// 销毁 tinymce
this.$emit('on-destroy')
window.tinymce.remove(`$#{this.Id}`)
},
methods: {
init () {
const self = this
this.Editor = window.tinymce.init({
// 默认配置
...this.DefaultConfig,
// 图片上传
images_upload_handler: function (blobInfo, success, failure) {
if (blobInfo.blob().size > self.maxSize) {
failure('文件体积过大')
}
if (self.accept.indexOf(blobInfo.blob().type) >= 0) {
uploadPic()
} else {
failure('图片格式错误')
}
function uploadPic () {
const xhr = new XMLHttpRequest()
const formData = new FormData()
xhr.withCredentials = self.withCredentials
xhr.open('POST', self.url)
xhr.onload = function () {
if (xhr.status !== 200) {
// 抛出 'on-upload-fail' 钩子
self.$emit('on-upload-fail')
failure('上传失败: ' + xhr.status)
return
}
const json = JSON.parse(xhr.responseText)
// 抛出 'on-upload-complete' 钩子
self.$emit('on-upload-complete' , [
json, success, failure
])
}
formData.append('file', blobInfo.blob())
xhr.send(formData)
}
},
// prop 内传入的的 config
...this.config,
// 挂载的 DOM 对象
selector: `#${this.Id}`,
setup: (editor) => {
// 抛出 'on-ready' 事件钩子
editor.on(
'init', () => {
self.loading = false
self.$emit('on-ready')
editor.setContent(self.value)
}
)
// 抛出 'input' 事件钩子,同步 value 数据
editor.on(
'input change undo redo', () => {
self.$emit('input', editor.getContent())
}
)
}
})
}
}
}
</script>
直接引入组件调用就行了
<template>
<mce-editor
:config = "Config"
v-model = "Value"
:url = "Url"
:max-size = "MaxSize"
:accept = "Accept"
:with-credentials = false
@on-ready = "onEditorReady"
@on-destroy = "onEditorDestroy"
@on-upload-success= "onEditorUploadComplete"
@on-upload-fail = "onEditorUploadFail"
></mce-editor>
</template>
但是作为一名优秀的程序员,这怎么可能够嘛。
下面说下打包的事情
塞入 webpack
为了加快页面载入速度就要首先解决载入文件过多的问题,而大部分时间用户并不需要每次打开页面都先加载一遍 editor 的核心文件,而 editor 本身也要按需加载内容,一开始想把每个 plugin 都搞成独立组件模块按需载入,但是这就要涉及到修改编辑器本身源码,或者说对 window.tinymce 删掉点特性,这些都太麻烦也都有风险,对后面的代码维护影响也大,索性就都先留着。
后面边做边改吧
还是以vue-cli为例
把官网下载的包塞到stataic
文件夹中
然后删掉index.html
模版中的 cdn 代码吧不需要了
当然这里有俩选择
要么做成一个异步组件,单独打包,按需载入
要么直接引入到main.js
中将包打成为一个巨无霸
所以我选择前者,
首先老规矩 引入编辑器主体
import '../../static/tinymce/tinymce.min.js'
然后刷新下页面,不出意外应该是报这么个错Uncaught SyntaxError: Unexpected token <
眼尖的朋友应该知道是怎么回事了theme.js:1
在默认配置下, tinymce 载入的 theme 的路径居然是这个
Request URL:http://localhost:8080/themes/modern/theme.js
然后我跑去官网搜了下 api 只搜到一个叫document_base_url的 api,但是根据多年程序员的直觉经验告诉我 不是这货(嗯,我在这里卡住了),网上翻了下各地文献,都没有啊,
那怎么办呢
于是我就跑去看源码…但是 4 万行…算了…
然后我就在控台打印了下 tinymce 对象,然后发现了一个叫baseURL
的string
对象,嗯,有希望了。
在源码里搜了下 baseURL
蹦出来这段代码 …. 算了有很多段…
大致思想就是通过当前 URI 拆出来个 baseURL,改掉就行了
window.tinymce.baseURL = '/static/tinymce'
如果需要载入的地址是另一个比如自己公司的 cdn 的路径,那改成全路径就行了,在qiankun中微服务使用
特别需要这个配置,否则插件主题按需加载 url 会相对主项目地址,导致加载不到相关依赖
window.tinymce.baseURL = 'http://cdn.xxx.com/static/tinymce'
#乾坤中使用
let base = window.__POWERED_BY_QIANKUN__ ?'/mall-code':''
window.tinymce.baseURL = base + '/static/tinymce4.7.5'
window.tinymce.init({})
在 init 前修改 baseURL,
貌似路径的问题解决了
但是新的问题又出现了,
插件下过来都是带 min 的,但默认载入的插件都是不带 min 的,一定是我源码没看仔细,
然后我又搜了一下代码
if (!baseURL && document.currentScript) {
src = document.currentScript.src;
if (src.indexOf('.min') != -1) {
suffix = '.min';
}
baseURL = src.substring(0, src.lastIndexOf('/'));
}
希望就在眼前,貌似是业务我载入的方式是直接导入到模块的,于是一个叫suffix
的默认值为空了,于是我去又加了行代码:
window.tinymce.suffix = '.min'
成功!
你看嘛,超级简单的是不是,根本不用改源码,网上说的动不动就去改源码什么的不要信啊不要信,大部分面向对象的事情改个默认值就行了。
对了,还记得前面的语言包嘛,
下过来塞到/static/tinymce/langs
文件夹里
然后删掉
import './zh_CN.js'
这行代码
在DefaultConfig
中放入一个新配置项
language: 'zh_CN'
好了,后面就是模块打包的事情了,
打包
前面打的包有一个问题是默认配置是载入 tinyMce 本体,那么就会造成这个包大概有 500k 的体积,如果这个组件不做异步载入的处理,那么对于某些业务来说就是灾难。虽然这么做打开只用载入一个文件,业务比较稳定。
但我觉得这样不优雅所以最后还是把它单独拎出来了。
同理,根据这个库本身的特性,我们完全可以把这么多个必须的plugin
按需要直接统一打成一个包,直接载入。这样,我们就又多了一个几百 k 的 plugins 包。
然后把plugins 包和 tinyMce 主体包
在不阻塞页面加载的情况下,做个懒加载提前缓存好文件方便后面使用,而组件本身在挂载前做个监听 window.tinymce 全局变量的方法,然后 cdn 控制下文件的过期时间即可。
这样,在保证了灵活度的前提下也保证了业务载入的速度。