首先是html的代碼,本人使用的element ui,使用的餓了么的上傳插件
<div
?v-loading="imageLoading"
? element-loading-text="請(qǐng)稍等,圖片上傳中">
? <div class="quill-editor"
? ? ? :content="article.content"
? ? ? ref="customQuillEditor"
? ? ? @change="onEditorChange($event)"
? ? ? @blur="onEditorBlur($event)"
? ? ? @focus="onEditorFocus($event)"
? ? ? @ready="onEditorReady($event)"
? ? ? v-quill:myQuillEditor="editorOption">
? ? style="display: none"
? ? class="avatar-uploader"
? ? action="http://127.0.0.1:8000/api/article"
? ? :show-file-list="false"
? ? :auto-upload="false"
? ? :on-change="imagesPreview">
? ? <img v-if="images" :src="images" class="avatar">
? ? <i v-else class="el-icon-plus avatar-uploader-icon" id="article-uploader">
</div>
定義一個(gè)toolbar常量
const toolbar= [
["bold", "italic", "underline", "strike"], // 加粗 斜體 下劃線 刪除線
// ["blockquote", "code-block"], // 引用? 代碼塊
? [{header:1 }, {header:2 }], // 1、2 級(jí)標(biāo)題
// [{ list: "ordered" }, { list: "bullet" }], // 有序、無序列表
// [{ script: "sub" }, { script: "super" }], // 上標(biāo)/下標(biāo)
// [{ indent: "-1" }, { indent: "+1" }], // 縮進(jìn)
// [{'direction': 'rtl'}],? ? ? ? ? ? ? ? ? ? ? ? // 文本方向
// [{ size: ["small", false, "large", "huge"] }], // 字體大小
// [{ header: [1, 2, 3, 4, 5, 6, false] }], // 標(biāo)題
// [{ color: [] }, { background: [] }], // 字體顏色、字體背景顏色
// [{ font: [] }], // 字體種類
// [{ align: [] }], // 對(duì)齊方式
// ["clean"], // 清除文本格式
? ["link", "image", "video"]// 鏈接、圖片、視頻
? ];
將配置注冊(cè)進(jìn)data中
editorOption: {
// some quill options
? modules: {
toolbar: {
container: toolbar,? // 工具欄
? ? ? handlers: {
'image':function (value) {
if (value) {
document.querySelector('#article-uploader').click();? ? ?//這里就是點(diǎn)擊上傳圖片按鈕會(huì)觸發(fā)的事件,然后,你這里直接觸發(fā)我們餓了么上傳圖片的按鈕點(diǎn)擊
? ? ? ? ? }else {
this.quill.format('image', false);
? ? ? ? ? }
}
}
}
}
}
在你的methods中將imagesPreview事件補(bǔ)全
imagesPreview(file){
//先進(jìn)行圖片的格式大小校驗(yàn)
let vm=this;
? const isJPG = file.type ==='image/jpeg' ||'image/jpg' ||'image/png' ||'image/gif';
? const isLt2M = file.size /1024 /1024 <2;
? if (!isJPG) {
this.$message.error('上傳頭像圖片只能是jpg,png,gif格式!');
? }
else if (!isLt2M) {
this.$message.error('上傳頭像圖片大小不能超過 2MB!');
? }else{
vm.imageLoading=true;
? ? const formData =new FormData();
? ? formData.append('images',file.raw);
? ? postAlbum(formData).then(res=>{
console.log(res.data.images);
????//獲取quill實(shí)例
? ? ? let quill=vm.myQuillEditor;? ?
? ? ? // 獲取光標(biāo)所在位置
? ? ? let length = quill.getLength();
? ? ? // 插入圖片? res.data.images為服務(wù)器返回的圖片地址
? ? ? quill.insertEmbed(length, 'image', res.data.images);
? ? ? // 調(diào)整光標(biāo)到最后
? ? ? quill.setSelection(length +1);
? ? //取消加載等待
? ? ? vm.imageLoading=false;
? ? ? console.log(vm.article.content);
? ? }).catch(error=>{
vm.$message.error('上傳失敗');
? ? ? vm.imageLoading=false;
? ? })
}
},
? ?