問題描述:
環境:webpack+vue+element
vue-quill-editor插入圖片的方式是將圖片轉為base64再放入內容中,直接存儲數據庫會導致內容過多占用大量的數據庫存儲空間,加載速度也會變慢,此方法是將圖片上傳到七牛返回到編輯器中,
解決方法
1.html內容 配合element-ul的上傳組件
apiurl是后台接口地址
<el-form-item label="項目簡介">
<div v-loading="imageLoading"
element-loading-text="請稍等,圖片上傳中">
<quill-editor ref="newEditor" v-model="form.intro" ></quill-editor>
<!-- 文件上傳input 將它隱藏-->
<el-upload style="display:none" :action="apiurl" :show-file-list="false" :before-upload='newEditorbeforeupload' :on-success='newEditorSuccess'
ref="uniqueId" id="uniqueId">
</el-upload >
</div>
</el-form-item>
2.javascrpit
vue實例化是在mounted注冊修改原來的圖片上傳事件
mounted(){
var imgHandler = async function(state) {
if (state) {
var fileInput =document.querySelector('#uniqueId input') //隱藏的file元素
fileInput.click() //觸發事件
}
}
this.$refs.newEditor.quill.getModule("toolbar").addHandler("image", imgHandler)
},
methods:添加方法即可
newEditorbeforeupload(file){ const isJPG = file.type === 'image/jpeg' ||file.type === 'image/png'; const isLt2M = file.size / 1024 / 1024 < 2; if (!isJPG) { this.$message.error('上傳圖片只能是 JPG或PNG 格式!'); } if (!isLt2M) { this.$message.error('上傳圖片大小不能超過 2MB!'); } if(isJPG && isLt2M)this.imageLoading =true return isJPG && isLt2M; }, //上傳圖片回調 newEditorSuccess(response, file, fileList){ if(response.status===1){ this.addImgRange = this.$refs.newEditor.quill.getSelection() this.$refs.newEditor.quill.insertEmbed(this.addImgRange != null?this.addImgRange.index:0, 'image',response.datas, Quill.sources.USER) } this.imageLoading =false },

ps:ue-quill-editor是基於適用於Vue2的富文本編輯器
github地址
