一、前端代码

Ueditor官网地址为: http://ueditor.baidu.com/website/download.html#ueditor 下载好之后,将Jsp版本解压,解压后文件夹改名为ueditor,将文件夹中的jsp目录删掉,之后将整个ueditor文件夹拷贝到Vue的public目录下,项目结构如下:

ueditor的jquery版本 ueditor vue_ueditor的jquery版本

vue中通过npm安装uediter组件

npm i vue-ueditor-wrap -S

将uediter简单封装成一个组件 elUeditor.vue,组件引入、参数配置直接看代码,代码如下:

<template>
    <div>
        <vue-ueditor-wrap :config="myConfig" v-model="content" @ready="ready"></vue-ueditor-wrap>
    </div>
</template>

<script>
    import VueUeditorWrap from 'vue-ueditor-wrap';
    import userInfoHelper from './token';

    export default {
        name: "elUeditor",
        components: {VueUeditorWrap},
        props: ['value'],
        data() {
            return {
                content: '',
                editor: null,
                myConfig: {
                    // 编辑器不自动被内容撑高
                    autoHeightEnabled: false,
                    // 工具栏是否可以浮动
                    autoFloatEnabled: false,
                    // 关闭自动保存
                    enableAutoSave: true,
                    // 初始容器高度
                    initialFrameHeight: 900,
                    // 初始容器宽度
                    initialFrameWidth: '100%',
                    // 上传文件接口
                    serverUrl: 'system/ueditor/upload?token=' + userInfoHelper.get().token,
                    // UEditor 资源文件的存放路径,如果你使用的是 vue-cli 生成的项目,通常不需要设置该选项,vue-ueditor-wrap 会自动处理常见的情况
                    UEDITOR_HOME_URL: '/ueditor/',
                    allowDivTransToP: false,
                    disabledTableInTable: false,
                    toolbars: [
                        [
                            'source', //源代码
                            'undo', //撤销
                            'redo', //重做
                            'formatmatch', //格式刷
                            'bold', //加粗
                            'italic', //斜体
                            'underline', //下划线
                            'strikethrough', //删除线
                            'superscript', //上标
                            'subscript', //下标
                            'justifyleft', //居左对齐
                            'justifyright', //居右对齐
                            'justifycenter', //居中对齐
                            'justifyjustify', //两端对齐
                            'rowspacingtop', //段前距
                            'rowspacingbottom', //段后距
                            'lineheight', //行间距
                            'anchor', //锚点
                            'indent', //首行缩进
                            // 'snapscreen', //截图
                            'fontborder', //字符边框
                            'blockquote', //引用
                            'pasteplain', //纯文本粘贴模式
                            'selectall', //全选
                            'horizontal', //分隔线
                            'removeformat', //清除格式
                            'time', //时间
                            'date', //日期
                            'insertcode', //代码语言
                            'inserttable', //插入表格
                            'insertrow', //前插入行
                            'insertcol', //前插入列
                            'mergeright', //右合并单元格
                            'mergedown', //下合并单元格
                            'deleterow', //删除行
                            'deletecol', //删除列
                            'splittorows', //拆分成行
                            'splittocols', //拆分成列
                            'splittocells', //完全拆分单元格
                            'edittable', //表格属性
                            'edittd', //单元格属性
                            'insertparagraphbeforetable', //"表格前插入行"
                            'deletecaption', //删除表格标题
                            'inserttitle', //插入标题
                            'mergecells', //合并多个单元格
                            'deletetable', //删除表格
                            'customstyle', //自定义标题
                            'fontfamily', //字体
                            'fontsize', //字号
                            'paragraph', //段落格式
                            'simpleupload', //单图上传
                            // 'insertvideo', //视频
                            // 'insertimage', //多图上传
                            'unlink', //取消链接
                            'link', //超链接
                            // 'emotion', //表情
                            'spechars', //特殊字符
                            'searchreplace', //查询替换
                            'map', //Baidu地图
                            'gmap', //Google地图
                            'forecolor', //字体颜色
                            'backcolor', //背景色
                            'insertorderedlist', //有序列表
                            'insertunorderedlist', //无序列表
                            'fullscreen', //全屏
                            'directionalityltr', //从左向右输入
                            'directionalityrtl', //从右向左输入
                            'pagebreak', //分页
                            'insertframe', //插入Iframe
                            'imagenone', //默认
                            'imageleft', //左浮动
                            'imageright', //右浮动
                            // 'attachment', //附件
                            'imagecenter', //居中
                            'wordimage', //图片转存
                            'edittip ', //编辑提示
                            'autotypeset', //自动排版
                            // 'webapp', //百度应用
                            'touppercase', //字母大写
                            'tolowercase', //字母小写
                            'background', //背景
                            'template', //模板
                            'scrawl', //涂鸦
                            'music', //音乐
                            'drafts', // 从草稿箱加载
                            // 'charts', // 图表
                            'cleardoc', //清空文档
                            'preview', //预览
                            'print', //打印
                            'help', //帮助
                        ]
                    ],
                }
            }
        },
        watch: {
            value(val) {
                this.content = val;
            },
            content(val) {
                let text = this.editor ? this.editor.getContentTxt() : "";
                this.$emit('change', val, text);
            }
        },
        mounted() {
            this.content = this.value;
        },
        methods: {
            ready(editorInstance) {
                this.editor = editorInstance;
            },
            insertDefineHtml(html) {
                this.editor.execCommand('inserthtml', html);
            }
        }
    }
</script>

其中 userInfoHelper 是我前端用于获取store中的token信息的,这里根据个人情况更改
组件使用方式:

<template>
    <div class="news">
        <el-ueditor :value="newsData.richText" @change="handleFormChangeContent" ref="uediter" 
        style="width: 676px;display: inline-block"></el-ueditor>
    </div>
</template>

<script>
    import elUeditor from './editor/elUeditor';
    export default {
        name: "News",
        components: {elUeditor},
        data() {
            return {
            }
        },
        methods: {
            handleFormChangeContent(val, text) {
                console.log("富文本:"+val);
                console.log("纯文本:"+text);
            }
        }
    }
</script>

可以通过insertDefineHtml()在光标处编辑插入内容

this.$refs.uediter.insertDefineHtml('插入的内容....');

二、后端代码

如果编辑器有上传功能的话,还需要做后端配置(后端是java springboot+maven项目)。
在resource创建配置文件ueditorConfig.json,配置文件内容如下:

{
    "imageActionName": "uploadimage",
    "imageFieldName": "upfile",
    "imageMaxSize": 2048000,
    "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
    "imageCompressEnable": true,
    "imageCompressBorder": 1600,
    "imageInsertAlign": "none",
    "imageUrlPrefix": "",
    "imagePathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",


    "scrawlActionName": "uploadscrawl",
    "scrawlFieldName": "upfile",
    "scrawlPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",
    "scrawlMaxSize": 2048000,
    "scrawlUrlPrefix": "",
    "scrawlInsertAlign": "none",

    "snapscreenActionName": "uploadimage",
    "snapscreenPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",
    "snapscreenUrlPrefix": "",
    "snapscreenInsertAlign": "none",

    "catcherLocalDomain": ["127.0.0.1", "localhost", "img.baidu.com"],
    "catcherActionName": "catchimage",
    "catcherFieldName": "source",
    "catcherPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",
    "catcherUrlPrefix": "",
    "catcherMaxSize": 2048000,
    "catcherAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"],

    "videoActionName": "uploadvideo",
    "videoFieldName": "upfile",
    "videoPathFormat": "/ueditor/jsp/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}",
    "videoUrlPrefix": "",
    "videoMaxSize": 102400000,
    "videoAllowFiles": [
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"],

    "fileActionName": "uploadfile",
    "fileFieldName": "upfile",
    "filePathFormat": "/ueditor/jsp/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}",
    "fileUrlPrefix": "",
    "fileMaxSize": 51200000,
    "fileAllowFiles": [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
    ],


    "imageManagerActionName": "listimage",
    "imageManagerListPath": "/ueditor/jsp/upload/image/",
    "imageManagerListSize": 20,
    "imageManagerUrlPrefix": "",
    "imageManagerInsertAlign": "none",
    "imageManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"],

    "fileManagerActionName": "listfile",
    "fileManagerListPath": "/ueditor/jsp/upload/file/",
    "fileManagerUrlPrefix": "",
    "fileManagerListSize": 20,
    "fileManagerAllowFiles": [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
    ]
}

然后添加controller上传接口,代码如下:

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * Ueditor富文本上传
 */
@RestController
public class UeditorRest extends Logging {

    @Qualifier("domesticOSSService")
    @Autowired
    private OSSService domesticOssService;
    @Autowired
    private BaseConfig.AppConfig appConfig;
    private static final String CONFIG = "config";
    private static final String UEDITOR_IMG_UPLOAD = "uploadimage";
    private static final String UEDITOR_VIDEO_UPLOAD = "uploadvideo";
    private static final String UEDITOR_UPLOAD_URL = "url";
    private static final String URDITOR_UPLOAD_ORIGINAL_FILE_NAME = "original";
    private static final String ACTION = "action";
    private static final String STATE = "state";
    private static final String UEDITOR_CONFIG_FILE = "ueditorConfig.json";
    private static final String UPLOAD_SUCCESS = "SUCCESS";


    /**
     * 获取配置和单图上传
     */
    @RequestMapping(value = "/system/ueditor/upload")
    @LogRecord(businessType = "获取配置和单图上传")
    public void ueditorUploadConfig(@RequestParam(value = "upfile", required = false) MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
        executeUeditor(request, response, file);
    }

    private void executeUeditor(HttpServletRequest request, HttpServletResponse response, MultipartFile file) {
        String action = request.getParameter(ACTION);
        String outStr = null;
        //此处在前端组件初始化的时候会通过上传接口获取配置信息,判断如果是获取配置信息,则返回配置信息
        if (StringUtils.equals(action, CONFIG)) {
            outStr = getUeditorConfig();
        }
        if (StringUtils.equals(action, UEDITOR_IMG_UPLOAD) || StringUtils.equals(action, UEDITOR_VIDEO_UPLOAD)) {
        //文件保存逻辑
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            String key = "com/news/" + file.getOriginalFilename() + System.currentTimeMillis() + "." + suffix;
            String bucketName = appConfig.getOssDomesticBucketName();
            boolean result = false;
            JSONObject json = new JSONObject();
            try {
                result = domesticOssService.uploadFile(bucketName, key, file.getBytes());
            } catch (IOException e) {
                json.put(STATE, "上传文件失败");
            }
            AssertUtil.isTrue(result, "上传文件失败");
            String url = domesticOssService.getUrl(bucketName, key);
            url = url.split("\\?")[0];
            //按要求格式返回
            json.put(STATE, UPLOAD_SUCCESS);
            json.put(UEDITOR_UPLOAD_URL, url);
            json.put(URDITOR_UPLOAD_ORIGINAL_FILE_NAME, file.getOriginalFilename());
            outStr = json.toString();
        }

        PrintWriter out;
        try {
            out = response.getWriter();
            if (StringUtils.isNotEmpty(outStr)) {
                out.print(outStr);
            }
        } catch (IOException e) {
            warn("UEditor接口调用发生异常");
        }
    }

    private String getUeditorConfig() {
        StringBuilder config = new StringBuilder();

        try {
            InputStream stream = getClass().getClassLoader().getResourceAsStream(UEDITOR_CONFIG_FILE);
            BufferedReader buff = new BufferedReader(new InputStreamReader(stream));
            String temp;
            while ((temp = buff.readLine()) != null) {
                config.append(temp);
            }
            //把配置文件中的注释去掉
            String configStr = config.toString().replaceAll("/\\*[\\s\\S]*?\\*/", "");
            return JSON.parseObject(configStr).toJSONString();
        } catch (Exception e) {
            warn("获取配置文件失败");
            return null;
        }
    }

}

其中初始化组件的配置请求信息:

ueditor的jquery版本 ueditor vue_ueditor的jquery版本_02


最终效果图:

ueditor的jquery版本 ueditor vue_html_03