TinyEditor.vue 11.6 KB
<template>
    <div>
        <Editor v-model="value_" :init="editorInit" @change="editorChange"/>
    </div>
</template>

<script lang="ts">
import {Component, Prop, Vue, Watch} from 'vue-facing-decorator';

//引入tinymce编辑器
import Editor from '@tinymce/tinymce-vue'
//
// //引入node_modules里的tinymce相关文件文件
import 'tinymce/themes/silver' //编辑器主题,不引入则报错
// import 'tinymce/models/dom'; //引入tinymce的dom模型
import 'tinymce/icons/default' //引入编辑器图标icon,不引入则不显示对应图标
// 引入编辑器插件(基本免费插件都在这儿了)
import 'tinymce/plugins/advlist' //高级列表
import 'tinymce/plugins/anchor' //锚点
import 'tinymce/plugins/autolink' //自动链接
import 'tinymce/plugins/autoresize' //编辑器高度自适应,注:plugins里引入此插件时,Init里设置的height将失效
import 'tinymce/plugins/autosave' //自动存稿
import 'tinymce/plugins/charmap' //特殊字符
import 'tinymce/plugins/code' //编辑源码
import 'tinymce/plugins/codesample' //代码示例
import 'tinymce/plugins/directionality' //文字方向
import 'tinymce/plugins/emoticons' //表情
import 'tinymce/plugins/fullpage' //文档属性
import 'tinymce/plugins/fullscreen' //全屏
import 'tinymce/plugins/help' //帮助
import 'tinymce/plugins/hr' //水平分割线
import 'tinymce/plugins/image' //插入编辑图片
import 'tinymce/plugins/importcss' //引入css
import 'tinymce/plugins/insertdatetime' //插入日期时间
import 'tinymce/plugins/link' //超链接
import 'tinymce/plugins/lists' //列表插件
import 'tinymce/plugins/media' //插入编辑媒体
import 'tinymce/plugins/nonbreaking' //插入不间断空格
import 'tinymce/plugins/pagebreak' //插入分页符
import 'tinymce/plugins/paste' //粘贴插件
import 'tinymce/plugins/preview' //预览
// import 'tinymce/plugins/print'//打印
import 'tinymce/plugins/quickbars' //快速工具栏
import 'tinymce/plugins/save' //保存
import 'tinymce/plugins/searchreplace' //查找替换
// import 'tinymce/plugins/spellchecker' //拼写检查,暂未加入汉化,不建议使用
// import 'tinymce/plugins/tabfocus' //切入切出,按tab键切出编辑器,切入页面其他输入框中
import 'tinymce/plugins/table' //表格
// import 'tinymce/plugins/template' //内容模板
import 'tinymce/plugins/textcolor' //文字颜色
import 'tinymce/plugins/textpattern' //快速排版
import 'tinymce/plugins/toc' //目录生成器
import 'tinymce/plugins/visualblocks' //显示元素范围
import 'tinymce/plugins/visualchars' //显示不可见字符
import 'tinymce/plugins/wordcount'
import axios from "axios";
import {message} from "ant-design-vue"; //字数统计
// import 'tinymce-i18n/langs/zh_CN'

const apiUrl = import.meta.env.VITE_API_BASE_URL;

@Component({components: {Editor}, emits: ['change', 'update:value']})
export default class TinyEditor extends Vue {

    @Prop({required: true})
    value: string;

    @Prop({required: false, type: Number, default: 400})
    height: number;

    value_: string = null;

    editorInit = null;


    created() {
        const baseUrl = import.meta.env.BASE_URL;
        this.editorInit = {
            language: 'zh_CN',  //语言类型
            base_url: '/tinymce', // 👈 关键:改为你设置的本地路径
            license_key: 'gpl',
            // width: 800,
            // skin_url: `${dev ? '' : '/web'}/tinymce/skins/ui/oxide`,  //皮肤:浅色
            // skin_url: '/tinymce/skins/ui/oxide-dark',//皮肤:暗色
            plugins: 'preview searchreplace autolink directionality paste visualblocks visualchars fullscreen image  link media code codesample table charmap  pagebreak nonbreaking anchor insertdatetime advlist lists wordcount autosave ',  //插件配置
            // toolbar: 'fullscreen undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | \
            //         styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | \
            //         table image media charmap  pagebreak insertdatetime preview | code selectall searchreplace visualblocks | indent2em lineheight formatpainter axupimgs',  //工具栏配置,设为false则隐藏
            toolbar: 'undo redo | bold italic | alignleft aligncenter alignright | image table | removeformat',
            // menubar: 'file edit',  //菜单栏配置,设为false则隐藏,不配置则默认显示全部菜单,也可自定义配置--查看 http://tinymce.ax-z.cn/configure/editor-appearance.php --搜索“自定义菜单”
            fontsize_formats: '12px 14px 16px 18px 20px 22px 24px 28px 32px 36px 48px 56px 72px',  //字体大小
            font_formats: '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;',  //字体样式
            //自带默认字体:'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'
            lineheight_formats: "0.5 0.8 1 1.2 1.5 1.75 2 2.5 3 4 5",  //行高配置,也可配置成"12px 14px 16px 20px"这种形式
            height: 400,  //注:引入autoresize插件时,此属性失效
            placeholder: '在这里输入文字',
            branding: false,  //tiny技术支持信息是否显示
            promotion: false,      // 关闭 “Powered by Tiny” 广告栏
            tinymceScriptSrc: '',  // 预防脚本来源记录
            // automatic_uploads: false,
            tracking: false,       // 👈 关闭追踪(这个是非官方但常见的尝试)
            resize: false,  //编辑器宽高是否可变,false-否,true-高可变,'both'-宽高均可,注意引号
            // statusbar: false,  //最下方的元素路径和字数统计那一栏是否显示
            elementpath: false,  //元素路径是否显示

            // relative_urls: false,  //false: tinymce将不再自动将文件路径由绝对转为相对
            // convert_urls: false,  //false: tinymce将不再自动处理文件路径
            content_style: "img { max-width: 100% !important; height: auto !important; }",  //直接自定义可编辑区域的css样式
            // content_css: '/tinycontent.css',  //以css文件方式自定义可编辑区域的css样式,css文件需自己创建并引入
            // images_upload_url: '/apib/api-upload/uploadimg',  //后端处理程序的url,建议直接自定义上传函数image_upload_handler,这个就可以不用了
            // images_upload_base_path: '/demo',  //相对基本路径--关于图片上传建议查看--http://tinymce.ax-z.cn/general/upload-images.php
            paste_data_images: true,  //图片是否可粘贴
            // image_title: true,
            // file_picker_types: 'image',
            images_upload_handler: (blobInfo, success, failure) => {
                console.debug(blobInfo.name());
                console.debug(blobInfo.filename());
                if (blobInfo.blob().size / 1024 / 1024 > 20) {
                    failure("上传失败,图片大小请控制在 20M 以内")
                } else {
                    let params = new FormData();
                    params.append('upload', blobInfo.blob());
                    const authToken = this.$auth.getToken();
                    let config = {
                        headers: {
                            "Authorization": 'Bearer ' + authToken,
                            "Content-Type": "multipart/form-data"
                        }
                    }
                    axios.post(`${apiUrl}upload/uploadRichTextImage`, params, config).then(res => {
                        if (res.status === 200) {
                            if (res.data.error) {
                                failure("上传失败")
                            } else {
                                console.log(res.data.url);
                                success(res.data.url)  //上传成功,在成功函数里填入图片路径
                            }
                        } else {
                            failure("上传失败")
                        }
                    }).catch(() => {
                        failure("上传出错,服务器开小差了呢")
                    })
                }
            },
            file_picker_callback: (callback, value, meta) => {
                //文件分类
                let filetype = '.pdf, .txt, .zip, .rar, .7z, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .mp3, .mp4, .out';
                //为不同插件指定文件类型及后端地址
                switch (meta.filetype) {
                    case 'image':
                        filetype = '.jpg, .jpeg, .png, .gif';
                        break;
                    case 'media':
                        filetype = '.mp3, .mp4';
                        break;
                    case 'file':
                    default:
                }
                //模拟出一个input用于添加本地文件
                let input = document.createElement('input');
                input.setAttribute('type', 'file');
                input.setAttribute('accept', filetype);
                input.click();
                input.onchange = (e) => {
                    console.log(e);
                    const file = e.target['files'][0];
                    let params = new FormData()
                    params.append('upload', file);
                    let config = {
                        headers: {
                            "Content-Type": "multipart/form-data"
                        }
                    }
                    axios.post(`${apiUrl}upload/uploadRichTextImage`, params, config).then(res => {
                        if (res.status === 200) {
                            if (res.data.error) {
                                message.error('上传失败');
                            } else {
                                callback(res.data.url, {text: res.data.fileName});
                            }
                        } else {
                            message.error('上传失败');
                        }
                    }).catch(() => {
                        message.error('上传出错,服务器开小差了呢');
                    })
                }
            },
            paste_preprocess: (plugin, args) => {
                // console.log(plugin, args);
                // args.content = 'helloworld';
            }
        };

        this.editorInit.base_url = baseUrl + 'tinymce';
        this.editorInit.height = this.height;
    }

    mounted() {
    }

    /**
     * 给下拉控件赋值
     * @param newValue
     * @param oldValue
     */
    @Watch('value', {deep: true, immediate: true})
    watchValue(newValue: any, oldValue: any): void {
        this.value_ = newValue;
    }

    editorChange(e) {
        if (e.type === 'change') {
            this.$emit('update:value', e.level.content);
            this.$emit('change', e);
        }
    }

}
</script>

<style scoped lang="less">

</style>