index.vue 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. <template>
  2. <div :class="{fullscreen:fullscreen}" class="tinymce-container" :style="{width:containerWidth}">
  3. <textarea :id="tinymceId" class="tinymce-textarea" />
  4. <div class="editor-custom-btn-container">
  5. <el-upload
  6. ref="upload"
  7. :multiple="true"
  8. action="/api/artical/uploadFile"
  9. :auto-upload="true"
  10. :show-file-list="false"
  11. :headers="headers"
  12. class="editor-upload-btn mlr10"
  13. :before-upload="uploadBefore"
  14. :on-success="uploadSuccess"
  15. >
  16. <el-button size="small" type="primary" >
  17. 添加附件
  18. </el-button>
  19. </el-upload>
  20. <editorImage color="#1890ff" class="editor-upload-btn mlr10" @successCBK="imageSuccessCBK" />
  21. </div>
  22. </div>
  23. </template>
  24. <script>
  25. /**
  26. * docs:
  27. * https://panjiachen.github.io/vue-element-admin-site/feature/component/rich-editor.html#tinymce
  28. */
  29. import editorImage from './components/EditorImage'
  30. import editorFile from './components/EditorFile'
  31. import plugins from './plugins'
  32. import toolbar from './toolbar'
  33. import load from './dynamicLoadScript'
  34. import axios from 'axios';
  35. // import tinymceCDN from '@/assets/tinymce.min.js'
  36. // why use this cdn, detail see https://github.com/PanJiaChen/tinymce-all-in-one
  37. const tinymceCDN = 'https://cdn.jsdelivr.net/npm/tinymce-all-in-one@4.9.3/tinymce.min.js'
  38. export default {
  39. name: 'Tinymce',
  40. components: { editorImage, editorFile },
  41. props: {
  42. id: {
  43. type: String,
  44. default: function() {
  45. return 'vue-tinymce-' + +new Date() + ((Math.random() * 1000).toFixed(0) + '')
  46. }
  47. },
  48. value: {
  49. type: String,
  50. default: ''
  51. },
  52. toolbar: {
  53. type: Array,
  54. required: false,
  55. default() {
  56. return []
  57. }
  58. },
  59. uploadUrl: {
  60. type: String,
  61. required: true
  62. },
  63. headers:{
  64. type: Object,
  65. required: true,
  66. default() {
  67. return {}
  68. }
  69. },
  70. menubar: {
  71. type: String,
  72. default: 'file edit insert view format table'
  73. },
  74. height: {
  75. type: [Number, String],
  76. required: false,
  77. default: 360
  78. },
  79. width: {
  80. type: [Number, String],
  81. required: false,
  82. default: 'auto'
  83. }
  84. },
  85. data() {
  86. return {
  87. hasChange: false,
  88. hasInit: false,
  89. tinymceId: this.id,
  90. fullscreen: false,
  91. languageTypeList: {
  92. 'en': 'en',
  93. 'zh': 'zh_CN',
  94. 'es': 'es_MX',
  95. 'ja': 'ja'
  96. }
  97. }
  98. },
  99. computed: {
  100. containerWidth() {
  101. const width = this.width
  102. if (/^[\d]+(\.[\d]+)?$/.test(width)) { // matches `100`, `'100'`
  103. return `${width}px`
  104. }
  105. return width
  106. }
  107. },
  108. watch: {
  109. value(val) {
  110. if (!this.hasChange && this.hasInit) {
  111. this.$nextTick(() =>
  112. window.tinymce.get(this.tinymceId).setContent(val || ''))
  113. }
  114. }
  115. },
  116. mounted() {
  117. this.init()
  118. },
  119. activated() {
  120. if (window.tinymce) {
  121. this.initTinymce()
  122. }
  123. },
  124. deactivated() {
  125. this.destroyTinymce()
  126. },
  127. destroyed() {
  128. this.destroyTinymce()
  129. },
  130. methods: {
  131. init() {
  132. load(tinymceCDN, (err) => {
  133. if (err) {
  134. this.$message.error(err.message)
  135. return
  136. }
  137. this.initTinymce()
  138. })
  139. },
  140. initTinymce() {
  141. const _this = this
  142. window.tinymce.init({
  143. selector: `#${this.tinymceId}`,
  144. language: this.languageTypeList['zh'],
  145. height: this.height,
  146. body_class: 'panel-body',
  147. object_resizing: true,
  148. // extended_valid_elements: 'img[style|class|src|border|alt|title|hspace|vspace|width|height|align|name|loading]',
  149. toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
  150. menubar: this.menubar,
  151. plugins: plugins,
  152. content_css : "tinymce.css",
  153. entity_encoding : "raw",
  154. remove_linebreaks : false,
  155. forced_root_block: false,
  156. force_br_newlines: true,
  157. // invalid_elements : "p, div, span",
  158. imagetools_toolbar: 'editimage',
  159. end_container_on_empty_block: true,
  160. powerpaste_word_import: 'clean',
  161. paste_merge_formats: false,
  162. code_dialog_height: 500,
  163. code_dialog_width: 900,
  164. advlist_bullet_styles: 'square',
  165. advlist_number_styles: 'default',
  166. imagetools_cors_hosts: ['smoa.ndjsxh.cn:8888'],
  167. default_link_target: '_blank',
  168. // table_default_styles: {
  169. // width: '80%',
  170. // border: '1',
  171. // cellspacing:"0",
  172. // cellpadding:"0"
  173. // },
  174. convert_urls: false,
  175. automatic_uploads: false,
  176. remove_linebreaks: false,
  177. link_title: true,
  178. relative_urls: false,
  179. paste_data_images: false,
  180. remove_script_host: false,
  181. nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
  182. init_instance_callback: editor => {
  183. if (_this.value) {
  184. editor.setContent(_this.value)
  185. }
  186. _this.hasInit = true
  187. editor.on('NodeChange Change KeyUp SetContent', () => {
  188. this.hasChange = true
  189. this.$emit('input', editor.getContent())
  190. })
  191. editor.on('paste', (evt) => {
  192. // 监听粘贴事件
  193. _this.onPaste(evt)
  194. })
  195. },
  196. setup(editor) {
  197. editor.on('FullscreenStateChanged', (e) => {
  198. _this.fullscreen = e.state
  199. })
  200. },
  201. // it will try to keep these URLs intact
  202. // https://www.tiny.cloud/docs-3x/reference/configuration/Configuration3x@convert_urls/
  203. // https://stackoverflow.com/questions/5196205/disable-tinymce-absolute-to-relative-url-conversions
  204. // convert_urls: true,
  205. // automatic_uploads: true
  206. // 整合七牛上传
  207. // images_upload_handler(blobInfo, success, failure, progress) {
  208. // console.log("images_upload_handler" )
  209. // progress(0);
  210. // const formData = new FormData();
  211. // // formData.append('file', blobInfo.blob() );
  212. // formData.append('file', blobInfo.blob(), blobInfo.filename());
  213. // axios.post(this.uploadUrl, formData).then(res => {
  214. // console.log("res", res)
  215. // success( res.data.filename );
  216. // }) .catch(err => {
  217. // failure("出现未知问题");
  218. // console.log(err);
  219. // });
  220. // }
  221. })
  222. },
  223. destroyTinymce() {
  224. const tinymce = window.tinymce.get(this.tinymceId)
  225. if (this.fullscreen) {
  226. tinymce.execCommand('mceFullScreen')
  227. }
  228. if (tinymce) {
  229. tinymce.destroy()
  230. }
  231. },
  232. uploadBefore(file) {
  233. const maxSize = file.size / 1024 / 1024 < 20;
  234. if (!maxSize) {
  235. this.$message.error('每个文件最大20M');
  236. }
  237. return maxSize;
  238. },
  239. uploadSuccess(res, file) {
  240. console.log( res, file.name )
  241. if (res.code === 200) {
  242. window.tinymce.get(this.tinymceId).insertContent(
  243. `<p><a target="_blank" style="cursor:hand;color:blue;display: block;" href="http://smoa.ndjsxh.cn:8888/preview/${res.data.filename}">${file.name}</a></p>`)
  244. } else {
  245. this.$message.error('图片上传失败')
  246. }
  247. },
  248. onPaste(e) {
  249. var items=e.clipboardData.items;
  250. var item = items[0];
  251. if ( item.kind != 'file' || item.type.indexOf('image/') == -1 ) {
  252. return
  253. }
  254. var file = item.getAsFile();
  255. const formData = new FormData()
  256. formData.append('file', file)
  257. // 上传图片
  258. axios.post(this.uploadUrl, formData, { headers: this.headers }).then(res => {
  259. if (res.data.code === 200) {
  260. window.tinymce.get(this.tinymceId).insertContent(`<img style="width:100%" src="http://smoa.ndjsxh.cn:8888/preview/${res.data.data.filename}" >`)
  261. } else {
  262. this.$message.error('图片上传失败,联系开发人员')
  263. }
  264. })
  265. },
  266. setContent(value) {
  267. window.tinymce.get(this.tinymceId).setContent(value)
  268. },
  269. getContent() {
  270. window.tinymce.get(this.tinymceId).getContent()
  271. },
  272. imageSuccessCBK(arr) {
  273. arr.forEach(v => window.tinymce.get(this.tinymceId).insertContent(`<img style="width:100%" src="${v.url}" >`))
  274. }
  275. }
  276. }
  277. </script>
  278. <style lang="scss" scoped>
  279. .tinymce-container {
  280. position: relative;
  281. line-height: normal;
  282. }
  283. .tinymce-container {
  284. ::v-deep {
  285. .mce-fullscreen {
  286. z-index: 10000;
  287. }
  288. }
  289. }
  290. .tinymce-textarea {
  291. visibility: hidden;
  292. z-index: -1;
  293. }
  294. .editor-custom-btn-container {
  295. position: absolute;
  296. right: 4px;
  297. top: 4px;
  298. /*z-index: 2005;*/
  299. }
  300. .fullscreen .editor-custom-btn-container {
  301. z-index: 10000;
  302. position: fixed;
  303. }
  304. .editor-upload-btn {
  305. display: inline-block;
  306. }
  307. .mlr10{ margin-left: 10px; margin-right: 10px;}
  308. </style>