vue中使用tinymce详细教程

2019-2-18

貌似这篇文章帮了大家一些小忙
最近tinymce出5.0版本了,下面的api还是4.x的,新版本可能会有些不适用了,最近业务繁忙,等哪天周末有时间的话我再做点更新 :)


前言

最近因业务需求在项目中嵌入了tinymce这个编辑器,用于满足平台给用户编辑各类新闻内容什么的业务需求,前后也花了不少时间体验和对比了市面上各类开源编辑器。

各大WYSIWYG编辑器的简单比较

UEditor: 因为已经不再维护了,需要大量修改源码,很多都是专门为jsp等服务器渲染项目写的代码需要删除, 然后越删越害怕越删越不敢用,依赖jquery,需要专门用js去parse编辑完成的内容,parse完的内容还可能污染全局css,兼容老浏览器还不错, 但是,我们不怎么考虑兼容IE。所以,告辞。

wangEditor: 中文文档,上手快,依赖jquery,功能少点要花时间去写插件,需要单独为图片上传功能写个接口,老项目忙着上线临时用过,感觉并不适合当前业务这么重的编辑功能于是放弃了。

Quill:api友好, 功能少,需要特定的css去解析文本(这点我不大喜欢),ui好看,适合作为论坛回帖功能使用。

CKEditor: CKEditor目前主流的还是4.x的版本,但是文档看着很瞎眼实在是提不起兴致去配置,草草用了下就放弃了,5.x版本刚从beta结束,需要指定专门的node以及npm版本,虽然功能强大配置灵活ui漂亮不过目前糟糕的兼容性基本是不可能出现在大众视野了。

KingEditor: 丑,不喜欢,不爱用

Draft-js: 知乎最近刚改的文本编辑器就是在draft的基础上开发的,依赖react, 弃。

Medium-editor: 虽然看着感觉很酷炫,但是,不适合我们的业务场景啊, api也简陋可怕。

trix: 嗯,又一个小而美,放弃

Slate: react,放弃

Bootstrap-wysiwyg: bootstrap, jquery, 放弃

tinymce: 文档好,功能强,bug少,无外部依赖,大家用了都说好,嗯,没错就是它了。

编辑器配置方面只要能看得懂英文耍起来还是比较简单的,适配中碰到的大部分问题都可以通过看文档解决,即便看文档解决不了网上也有大量的文章能告诉你怎么配置能解决。

当然了,主要是我这里需要解决一些别人觉得超简单自己一想都很烦人的需求,比如:

  1. word文档粘贴进来要带格式
  2. 兼容移动端
  3. word文档粘贴进来要正常显示并且还要兼容移动端
  4. 电脑网页里粘贴进来内容要正常显示并且排版还不能乱
  5. 电脑网页拷过来的内容还要兼容到移动端

初始化

因为tinymce的Plugins是按需加载的
为了能先快速上手这个编辑器
就先在vue-cli的index.html中默认塞入一条在线cdn地址


 
 
   
   
   
   
  1. <script src="https://cdn.bootcss.com/tinymce/4.7.4/tinymce.min.js"> script>

记得去下载语言包到本地,
然后就在文件内引入

import './zh_CN.js'
 
 
   
   
   
   

后面有机会再写下单独打包的事项,毕竟这货体积还不小。

插入vue组件模板


 
 
   
   
   
   
  1. <template>
  2. <div>
  3. <textarea :id= "Id"> textarea>
  4. div>
  5. template>

记得一定要在textarea外面包一层div,不然...你自己试试看就知道了。

组件基础配置

将tinymce通过指定的selector挂载到组件中


 
 
   
   
   
   
  1. <template>
  2. <div>
  3. <textarea :id= "Id"> textarea>
  4. div>
  5. template>
  6. <script>
  7. import './zh_CN.js'
  8. export default {
  9. data () {
  10. const Id = Date.now()
  11. return {
  12. Id: Id,
  13. Editor: null,
  14. DefaultConfig: {}
  15. }
  16. },
  17. props: {
  18. value: {
  19. default: '',
  20. type: String
  21. },
  22. config: {
  23. type: Object,
  24. default: () => {
  25. return {
  26. theme: 'modern',
  27. height: 300
  28. }
  29. }
  30. }
  31. },
  32. mounted () {
  33. this.init()
  34. },
  35. beforeDestroy () {
  36. // 销毁tinymce
  37. this.$emit( 'on-destroy')
  38. window.tinymce.remove( `#${this.Id}`)
  39. },
  40. methods: {
  41. init () {
  42. const self = this
  43. this.Editor = window.tinymce.init({
  44. // 默认配置
  45. ...this.DefaultConfig,
  46. // prop内传入的的config
  47. ...this.config,
  48. // 挂载的DOM对象
  49. selector: `#${this.Id}`,
  50. setup: (editor) => {
  51. // 抛出 'on-ready' 事件钩子
  52. editor.on(
  53. 'init', () => {
  54. self.loading = false
  55. self.$emit( 'on-ready')
  56. editor.setContent(self.value)
  57. }
  58. )
  59. // 抛出 'input' 事件钩子,同步value数据
  60. editor.on(
  61. 'input change undo redo', () => {
  62. self.$emit( 'input', editor.getContent())
  63. }
  64. )
  65. }
  66. })
  67. }
  68. }
  69. }
  70. script>

好了,组件基本的初始化完成,后面正式开始踩坑之旅

API

具体内容看官网的API就行,英语不好的用chrome翻译下对照着demo也能看个七七八八,当然主要原因还是我比较懒。

我这边根据自身业务需求在组件的data内写了个默认配置


 
 
   
   
   
   
  1. DefaultConfig: {
  2. // GLOBAL
  3. height: 500,
  4. theme: 'modern',
  5. menubar: false,
  6. 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 `,
  7. plugins: `
  8. paste
  9. importcss
  10. image
  11. code
  12. table
  13. advlist
  14. fullscreen
  15. link
  16. media
  17. lists
  18. textcolor
  19. colorpicker
  20. hr
  21. preview
  22. `,
  23. // CONFIG
  24. forced_root_block: 'p',
  25. force_p_newlines: true,
  26. importcss_append: true,
  27. // CONFIG: ContentStyle 这块很重要, 在最后呈现的页面也要写入这个基本样式保证前后一致, `table`和`img`的问题基本就靠这个来填坑了
  28. content_style: `
  29. * { padding:0; margin:0; }
  30. html, body { height:100%; }
  31. img { max-width:100%; display:block;height:auto; }
  32. a { text-decoration: none; }
  33. iframe { width: 100%; }
  34. p { line-height:1.6; margin: 0px; }
  35. table { word-wrap:break-word; word-break:break-all; max-width:100%; border:none; border-color:#999; }
  36. .mce-object-iframe { width:100%; box-sizing:border-box; margin:0; padding:0; }
  37. ul,ol { list-style-position:inside; }
  38. `,
  39. insert_button_items: 'image link | inserttable',
  40. // CONFIG: Paste
  41. paste_retain_style_properties: 'all',
  42. paste_word_valid_elements: '*[*]', // word需要它
  43. paste_data_images: true, // 粘贴的同时能把内容里的图片自动上传,非常强力的功能
  44. paste_convert_word_fake_lists: false, // 插入word文档需要该属性
  45. paste_webkit_styles: 'all',
  46. paste_merge_formats: true,
  47. nonbreaking_force_tab: false,
  48. paste_auto_cleanup_on_paste: false,
  49. // CONFIG: Font
  50. fontsize_formats: '10px 11px 12px 14px 16px 18px 20px 24px',
  51. // CONFIG: StyleSelect
  52. style_formats: [
  53. {
  54. title: '首行缩进',
  55. block: 'p',
  56. styles: { 'text-indent': '2em' }
  57. },
  58. {
  59. title: '行高',
  60. items: [
  61. { title: '1', styles: { 'line-height': '1' }, inline: 'span'},
  62. { title: '1.5', styles: { 'line-height': '1.5' }, inline: 'span'},
  63. { title: '2', styles: { 'line-height': '2' }, inline: 'span'},
  64. { title: '2.5', styles: { 'line-height': '2.5' }, inline: 'span'},
  65. { title: '3', styles: { 'line-height': '3' }, inline: 'span'}
  66. ]
  67. }
  68. ],
  69. // FontSelect
  70. font_formats: `
  71. 微软雅黑=微软雅黑;
  72. 宋体=宋体;
  73. 黑体=黑体;
  74. 仿宋=仿宋;
  75. 楷体=楷体;
  76. 隶书=隶书;
  77. 幼圆=幼圆;
  78. Andale Mono=andale mono,times;
  79. Arial=arial, helvetica,
  80. sans-serif;
  81. Arial Black=arial black, avant garde;
  82. Book Antiqua=book antiqua,palatino;
  83. Comic Sans MS=comic sans ms,sans-serif;
  84. Courier New=courier new,courier;
  85. Georgia=georgia,palatino;
  86. Helvetica=helvetica;
  87. Impact=impact,chicago;
  88. Symbol=symbol;
  89. Tahoma=tahoma,arial,helvetica,sans-serif;
  90. Terminal=terminal,monaco;
  91. Times New Roman=times new roman,times;
  92. Trebuchet MS=trebuchet ms,geneva;
  93. Verdana=verdana,geneva;
  94. Webdings=webdings;
  95. Wingdings=wingdings,zapf dingbats`,
  96. // Tab
  97. tabfocus_elements: ':prev,:next',
  98. object_resizing: true,
  99. // Image
  100. imagetools_toolbar: 'rotateleft rotateright | flipv fliph | editimage imageoptions'
  101. }

因为本人比较懒,以上配置导出的代码可能会有代码注入的风险,建议保存的时候再前后端都做下注入过滤,不过一般数据安全问题主要还是服务器那边的事情?。

后面的图片上传可以单独拆出来做个小配置,直接写到props里好了。


 
 
   
   
   
   
  1. url: {
  2. default: '',
  3. type: String
  4. },
  5. accept: {
  6. default: 'image/jpeg, image/png',
  7. type: String
  8. },
  9. maxSize: {
  10. default: 2097152,
  11. type: Number
  12. },
  13. withCredentials: {
  14. default: false,
  15. type: Boolean
  16. }

然后把这套东西塞到init配置里


 
 
   
   
   
   
  1. // 图片上传
  2. images_upload_handler: function (blobInfo, success, failure) {
  3. if (blobInfo.blob().size > self.maxSize) {
  4. failure( '文件体积过大')
  5. }
  6. if ( self.accept.indexOf(blobInfo.blob().type) >= 0) {
  7. uploadPic()
  8. } else {
  9. failure( '图片格式错误')
  10. }
  11. function uploadPic () {
  12. const xhr = new XMLHttpRequest()
  13. const formData = new FormData()
  14. xhr.withCredentials = self.withCredentials
  15. xhr.open( 'POST', self.url)
  16. xhr.onload = function () {
  17. if (xhr.status !== 200) {
  18. // 抛出 'on-upload-fail' 钩子
  19. self.$emit( 'on-upload-fail')
  20. failure( '上传失败: ' + xhr.status)
  21. return
  22. }
  23. const json = JSON.parse(xhr.responseText)
  24. // 抛出 'on-upload-success' 钩子
  25. self.$emit( 'on-upload-complete' , [
  26. json, success, failure
  27. ])
  28. }
  29. formData.append( 'file', blobInfo.blob())
  30. xhr.send(formData)
  31. }
  32. }

至此, 一个组件的封装基本算是完成了

看下初阶成果


 
 
   
   
   
   
  1. <template>
  2. <div>
  3. <textarea :id= "Id"> textarea>
  4. div>
  5. template>
  6. <script>
  7. import './zh_CN.js'
  8. export default {
  9. data () {
  10. const Id = Date.now()
  11. return {
  12. Id: Id,
  13. Editor: null,
  14. DefaultConfig: {
  15. // GLOBAL
  16. height: 500,
  17. theme: 'modern',
  18. menubar: false,
  19. 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 `,
  20. plugins: `
  21. paste
  22. importcss
  23. image
  24. code
  25. table
  26. advlist
  27. fullscreen
  28. link
  29. media
  30. lists
  31. textcolor
  32. colorpicker
  33. hr
  34. preview
  35. `,
  36. // CONFIG
  37. forced_root_block: 'p',
  38. force_p_newlines: true,
  39. importcss_append: true,
  40. // CONFIG: ContentStyle 这块很重要, 在最后呈现的页面也要写入这个基本样式保证前后一致, `table`和`img`的问题基本就靠这个来填坑了
  41. content_style: `
  42. * { padding:0; margin:0; }
  43. html, body { height:100%; }
  44. img { max-width:100%; display:block;height:auto; }
  45. a { text-decoration: none; }
  46. iframe { width: 100%; }
  47. p { line-height:1.6; margin: 0px; }
  48. table { word-wrap:break-word; word-break:break-all; max-width:100%; border:none; border-color:#999; }
  49. .mce-object-iframe { width:100%; box-sizing:border-box; margin:0; padding:0; }
  50. ul,ol { list-style-position:inside; }
  51. `,
  52. insert_button_items: 'image link | inserttable',
  53. // CONFIG: Paste
  54. paste_retain_style_properties: 'all',
  55. paste_word_valid_elements: '*[*]', // word需要它
  56. paste_data_images: true, // 粘贴的同时能把内容里的图片自动上传,非常强力的功能
  57. paste_convert_word_fake_lists: false, // 插入word文档需要该属性
  58. paste_webkit_styles: 'all',
  59. paste_merge_formats: true,
  60. nonbreaking_force_tab: false,
  61. paste_auto_cleanup_on_paste: false,
  62. // CONFIG: Font
  63. fontsize_formats: '10px 11px 12px 14px 16px 18px 20px 24px',
  64. // CONFIG: StyleSelect
  65. style_formats: [
  66. {
  67. title: '首行缩进',
  68. block: 'p',
  69. styles: { 'text-indent': '2em' }
  70. },
  71. {
  72. title: '行高',
  73. items: [
  74. { title: '1', styles: { 'line-height': '1' }, inline: 'span'},
  75. { title: '1.5', styles: { 'line-height': '1.5' }, inline: 'span'},
  76. { title: '2', styles: { 'line-height': '2' }, inline: 'span'},
  77. { title: '2.5', styles: { 'line-height': '2.5' }, inline: 'span'},
  78. { title: '3', styles: { 'line-height': '3' }, inline: 'span'}
  79. ]
  80. }
  81. ],
  82. // FontSelect
  83. font_formats: `
  84. 微软雅黑=微软雅黑;
  85. 宋体=宋体;
  86. 黑体=黑体;
  87. 仿宋=仿宋;
  88. 楷体=楷体;
  89. 隶书=隶书;
  90. 幼圆=幼圆;
  91. Andale Mono=andale mono,times;
  92. Arial=arial, helvetica,
  93. sans-serif;
  94. Arial Black=arial black, avant garde;
  95. Book Antiqua=book antiqua,palatino;
  96. Comic Sans MS=comic sans ms,sans-serif;
  97. Courier New=courier new,courier;
  98. Georgia=georgia,palatino;
  99. Helvetica=helvetica;
  100. Impact=impact,chicago;
  101. Symbol=symbol;
  102. Tahoma=tahoma,arial,helvetica,sans-serif;
  103. Terminal=terminal,monaco;
  104. Times New Roman=times new roman,times;
  105. Trebuchet MS=trebuchet ms,geneva;
  106. Verdana=verdana,geneva;
  107. Webdings=webdings;
  108. Wingdings=wingdings,zapf dingbats`,
  109. // Tab
  110. tabfocus_elements: ':prev,:next',
  111. object_resizing: true,
  112. // Image
  113. imagetools_toolbar: 'rotateleft rotateright | flipv fliph | editimage imageoptions'
  114. }
  115. }
  116. },
  117. props: {
  118. value: {
  119. default: '',
  120. type: String
  121. },
  122. config: {
  123. type: Object,
  124. default: () => {
  125. return {
  126. theme: 'modern',
  127. height: 300
  128. }
  129. }
  130. },
  131. url: {
  132. default: '',
  133. type: String
  134. },
  135. accept: {
  136. default: 'image/jpeg, image/png',
  137. type: String
  138. },
  139. maxSize: {
  140. default: 2097152,
  141. type: Number
  142. },
  143. withCredentials: {
  144. default: false,
  145. type: Boolean
  146. }
  147. },
  148. mounted () {
  149. this.init()
  150. },
  151. beforeDestroy () {
  152. // 销毁tinymce
  153. this.$emit( 'on-destroy')
  154. window.tinymce.remove( `$#{this.Id}`)
  155. },
  156. methods: {
  157. init () {
  158. const self = this
  159. this.Editor = window.tinymce.init({
  160. // 默认配置
  161. ...this.DefaultConfig,
  162. // 图片上传
  163. images_upload_handler: function (blobInfo, success, failure) {
  164. if (blobInfo.blob().size > self.maxSize) {
  165. failure( '文件体积过大')
  166. }
  167. if (self.accept.indexOf(blobInfo.blob().type) >= 0) {
  168. uploadPic()
  169. } else {
  170. failure( '图片格式错误')
  171. }
  172. function uploadPic () {
  173. const xhr = new XMLHttpRequest()
  174. const formData = new FormData()
  175. xhr.withCredentials = self.withCredentials
  176. xhr.open( 'POST', self.url)
  177. xhr.onload = function () {
  178. if (xhr.status !== 200) {
  179. // 抛出 'on-upload-fail' 钩子
  180. self.$emit( 'on-upload-fail')
  181. failure( '上传失败: ' + xhr.status)
  182. return
  183. }
  184. const json = JSON.parse(xhr.responseText)
  185. // 抛出 'on-upload-complete' 钩子
  186. self.$emit( 'on-upload-complete' , [
  187. json, success, failure
  188. ])
  189. }
  190. formData.append( 'file', blobInfo.blob())
  191. xhr.send(formData)
  192. }
  193. },
  194. // prop内传入的的config
  195. ...this.config,
  196. // 挂载的DOM对象
  197. selector: `#${this.Id}`,
  198. setup: (editor) => {
  199. // 抛出 'on-ready' 事件钩子
  200. editor.on(
  201. 'init', () => {
  202. self.loading = false
  203. self.$emit( 'on-ready')
  204. editor.setContent(self.value)
  205. }
  206. )
  207. // 抛出 'input' 事件钩子,同步value数据
  208. editor.on(
  209. 'input change undo redo', () => {
  210. self.$emit( 'input', editor.getContent())
  211. }
  212. )
  213. }
  214. })
  215. }
  216. }
  217. }
  218. script>

直接引入组件调用就行了


 
 
   
   
   
   

但是作为一名优秀的程序员,这怎么可能够嘛。
下面说下打包的事情

塞入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对象,然后发现了一个叫baseURLstring对象,嗯,有希望了。
在源码里搜了下baseURL
蹦出来这段代码 .... 算了有很多段...
大致思想就是通过当前URI拆出来个baseURL,改掉就行了

window.tinymce.baseURL = '/static/tinymce'
 
 
   
   
   
   

如果需要载入的地址是另一个比如自己公司的cdn的路径,那改成全路径就行了

window.tinymce.baseURL = 'http://cdn.xxx.com/static/tinymce'
 
 
   
   
   
   

貌似路径的问题解决了

但是新的问题又出现了,
插件下过来都是带min的,但默认载入的插件都是不带min的,一定是我源码没看仔细,
然后我又搜了一下代码


 
 
   
   
   
   
  1. if (!baseURL && document.currentScript) {
  2. src = document.currentScript.src;
  3. if (src.indexOf( '.min') != -1) {
  4. suffix = '.min';
  5. }
  6. baseURL = src.substring( 0, src.lastIndexOf( '/'));
  7. }

希望就在眼前,貌似是业务我载入的方式是直接导入到模块的,于是一个叫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控制下文件的过期时间即可。
这样,在保证了灵活度的前提下也保证了业务载入的速度。

完,感谢阅读。

你可能感兴趣的:(前端,vue,vue,富文本,tinymce)