日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > vue >内容正文

vue

vue整合ueditor

發布時間:2024/8/1 vue 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 vue整合ueditor 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、前端代碼

Ueditor官網地址為: http://ueditor.baidu.com/website/download.html#ueditor
下載好之后,將Jsp版本解壓,解壓后文件夾改名為ueditor,將文件夾中的jsp目錄刪掉,之后將整個ueditor文件夾拷貝到Vue的public目錄下,項目結構如下:

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")@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接口調用發生異常");}}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;}}}

其中初始化組件的配置請求信息:

最終效果圖:

總結

以上是生活随笔為你收集整理的vue整合ueditor的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。