TinyMCE是一款易用、且功能強大的所見即所得的富文本編輯器。同類程序有:UEditor、Kindeditor、Simditor、CKEditor、wangEditor、Suneditor、froala等等。
tiny中文文檔:http://tinymce.ax-z.cn/
本文介紹如何在vue項目中,使用TinyMCE實現富文本基本功能。包括圖片上傳,表格創建等功能,也有些不明之處。
1、下載安裝,node_modules中會有 @tinymce 和 tinymce 依賴文件。
// 安裝tinymce-vue npm install @tinymce/tinymce-vue -S
// 安裝tinymce npm install tinymce -S
// package.json文件中版本 "@tinymce/tinymce-vue": "^3.2.1", "tinymce": "^5.2.2",
2、下載中文語言包,中文語言包
該項目中,我把語言包放到了public文件夾下。
在public目錄下新建langs,將上面下載的語言包解壓到該目錄,如下圖示例:
3、使用
<template> <Editor :init="initConfig" v-model="content" >Init text</Editor> </template> <script lang="ts"> import Vue from 'vue' import 'tinymce/themes/mobile/theme.js' import Editor from '@tinymce/tinymce-vue' export default Vue.extend({ components: { Editor }, data () { return { content: '', initConfig: { statusbar: false, // 固定寬高 width: 850, height: 400, /* eslint-disable max-len */ // plugins配置參數用於指定哪些插件被用在當前編輯器實例中 plugins: 'image link table lists imagetools', // 工具欄上添加相應的按鈕 toolbar: 'formatselect | bold italic underline strikethrough forecolor backcolor | link image table | alignleft aligncenter alignright alignjustify | numlist bullist outdent indent | removeformat', // 頂部菜單欄顯示 menubar: false, // 中文語言包路徑 language_url: '/langs/zh_CN.js', language: 'zh_CN', target_list: [ { title: '當前窗口', value: '' }, { title: '新窗口', value: '_blank' }, ], /* 我們的自定義圖像選擇器 */ file_picker_types: 'image', // @ts-ignore file_picker_callback: function (cb, value, meta) { let input = document.createElement('input') input.setAttribute('type', 'file') input.setAttribute('accept', 'image/*') input.onchange = function () { // @ts-ignore let file = this.files[0] let reader = new FileReader() reader.onload = function () { /* Note: Now we need to register the blob in TinyMCEs image blob registry. */ let id = 'blobid' + (new Date()).getTime() // @ts-ignore let blobCache = tinymce.activeEditor.editorUpload.blobCache // @ts-ignore let base64 = reader.result.split(',')[1] console.log(reader.result) let blobInfo = blobCache.create(id, file, base64) blobCache.add(blobInfo) cb(blobInfo.blobUri(), { title: file.name }) } reader.readAsDataURL(file) } input.click() }, }, /* eslint-enable max-len */ } }, methods: { onChange (e: any) { this.$emit('input', this.content) console.log(e.type, this.content) }, }, }) </script>
4、 有點問題:報錯了了了。
我需要在index.html文件中引入該代碼,這樣不會報錯了......
<script src="https://lib.baomitu.com/jquery/1.12.4/jquery.min.js" defer></script> <script crossorigin="anonymous" defer src="https://lib.baomitu.com/tinymce/5.0.3/tinymce.min.js"></script>
附其他的一下實現方式:
https://liubing.me/vue-tinymce-5.html