vue整合ueditor
生活随笔
收集整理的這篇文章主要介紹了
vue整合ueditor
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一、前端代碼
Ueditor官網(wǎng)地址為: http://ueditor.baidu.com/website/download.html#ueditor
下載好之后,將Jsp版本解壓,解壓后文件夾改名為ueditor,將文件夾中的jsp目錄刪掉,之后將整個ueditor文件夾拷貝到Vue的public目錄下,項目結(jié)構(gòu)如下:
vue中通過npm安裝uediter組件
npm i vue-ueditor-wrap -S將uediter簡單封裝成一個組件 elUeditor.vue,組件引入、參數(shù)配置直接看代碼,代碼如下:
<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: {// 編輯器不自動被內(nèi)容撐高autoHeightEnabled: false,// 工具欄是否可以浮動autoFloatEnabled: false,// 關(guān)閉自動保存enableAutoSave: true,// 初始容器高度initialFrameHeight: 900,// 初始容器寬度initialFrameWidth: '100%',// 上傳文件接口serverUrl: 'system/ueditor/upload?token=' + userInfoHelper.get().token,// UEditor 資源文件的存放路徑,如果你使用的是 vue-cli 生成的項目,通常不需要設(shè)置該選項,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', //圖片轉(zhuǎn)存'edittip ', //編輯提示'autotypeset', //自動排版// 'webapp', //百度應(yīng)用'touppercase', //字母大寫'tolowercase', //字母小寫'background', //背景'template', //模板'scrawl', //涂鴉'music', //音樂'drafts', // 從草稿箱加載// 'charts', // 圖表'cleardoc', //清空文檔'preview', //預(yù)覽'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信息的,這里根據(jù)個人情況更改
組件使用方式:
可以通過insertDefineHtml()在光標處編輯插入內(nèi)容
this.$refs.uediter.insertDefineHtml('插入的內(nèi)容....');二、后端代碼
如果編輯器有上傳功能的話,還需要做后端配置(后端是java springboot+maven項目)。
在resource創(chuàng)建配置文件ueditorConfig.json,配置文件內(nèi)容如下:
然后添加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")@Autowiredprivate OSSService domesticOssService;@Autowiredprivate 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接口調(diào)用發(fā)生異常");}}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;}}}其中初始化組件的配置請求信息:
最終效果圖:
總結(jié)
以上是生活随笔為你收集整理的vue整合ueditor的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VB程序设计—For循环结构
- 下一篇: jdk6或者7Base64转码与解码