vue集成一個支持圖片縮放拖拽的富文本編輯器
根據業務要求,需要能夠上傳圖片,且上傳的圖片能在移動端中占滿屏幕寬度,故需要能等比縮放上傳的圖片,還需要能拖拽、縮放、改變圖片大小。嘗試多個第三方富文本編輯器,很難找到一個完美符合自己要求的編輯器。經過多次嘗試,最終選擇了wangEditor富文本編輯器。 最初使用的是vue2Editor富文本編輯器,vue2Editor本身是不支持圖片拖拽的,但是提供了可配置圖片拖拽的方法,需要借助Quill.js來實現圖片拖拽。雖然滿足了業務需求,但是在移動端展示的效果不是很理想。 此次編輯器主要是上傳的富文本需要在移動端進行展示,為了達到理想效果,需要能修改圖片百分比,當設置img標簽的width屬性為100% 時,就可以滿足需求。最近發新版本(第四版 v4)的wangEditor可以滿足需求,最終選擇了它用于實際開發中。
效果圖:安裝插件
npm i wangeditor --save// oryarn add wangeditor
編輯器配置
<template><div class='w_editor'><!-- 富文本編輯器 --><div id='w_view'></div></div></template><script>// 引入富文本import WE from 'wangeditor';// 引入elementUI Message模塊(用于提示信息)import { Message } from 'element-ui';export default {name: 'WEditor',props: {// 默認值defaultText: { type: String, default: '' },// 富文本更新的值richText: { type: String, default: '' }},data() {return {// 編輯器實例editor: null,// 富文本菜單選項配置menuItem: ['head','bold','fontSize','fontName','italic','underline','indent','lineHeight','foreColor','backColor','link','list','justify','image','video']};},watch: {// 監聽默認值defaultText(nv, ov) {if (nv != '') {this.editor.txt.html(nv);this.$emit('update:rich-text', nv);}}},mounted() {this.initEditor();},methods: {// 初始化編輯器initEditor() {// 獲取編輯器dom節點const editor = new WE('#w_view');// 配置編輯器editor.config.showLinkImg = false; /* 隱藏插入網絡圖片的功能 */editor.config.onchangeTimeout = 400; /* 配置觸發 onchange 的時間頻率,默認為 200ms */editor.config.uploadImgMaxLength = 1; /* 限制一次最多能傳幾張圖片 */// editor.config.showFullScreen = false; /* 配置全屏功能按鈕是否展示 */editor.config.menus = [...this.menuItem]; /* 自定義系統菜單 */// editor.config.uploadImgMaxSize = 5 * 1024 * 1024 /* 限制圖片大小 */;editor.config.customAlert = err => {Message.error(err);};// 監控變化,同步更新數據editor.config.onchange = newHtml => {// 異步更新組件富文本值的變化this.$emit('update:rich-text', newHtml);};// 自定義上傳圖片editor.config.customUploadImg = (resultFiles, insertImgFn) => {/** * resultFiles:圖片上傳文件流 * insertImgFn:插入圖片到富文本 * 返回結果為生成的圖片URL地址 * */// 此方法為自己封賺改寫的阿里云圖片OSS直傳插件。this.$oss(resultFiles[0], resultFiles[0]['name']).then(url => {!!url && insertImgFn(url); /* oss圖片上傳,將圖片插入到編輯器中 */});};// 創建編輯器editor.create();this.editor = editor;}},beforeDestroy() {// 銷毀編輯器this.editor.destroy();this.editor = null;}};</script>
注: 具體參數配置請參考編輯器文檔使用說明。
組件中使用抽離的編輯器:<template><div class='editor'><el-card shadow='never'><div slot='header' class='clearfix'><span>富文本編輯器</span></div><div class='card_center'><WEditor :defaultText='defaultText' :richText.sync='richText' /></div></el-card></div></template><script>// 引入封裝好的編輯器import WEditor from '@/components/WEditor';export default {name: 'Editor',components: { WEditor },data() {return {// 默認值defaultText: '',// 富文本更新的值richText: ''};},created() {// 等待組件加載完畢賦值this.$nextTick(() => {this.defaultText = `<p style='text-align: center; '><img src='https://tr-mba.oss-cn-beijing.aliyuncs.com/picture/202010/20_222430_8011.png' style='text-align: center; max-width: 100%;'></p>`;});}};</script>
以上就是vue集成一個支持圖片縮放拖拽的富文本編輯器的詳細內容,更多關于vue 富文本編輯器的資料請關注好吧啦網其它相關文章!
相關文章:
