vue使用vue-quill-editor富文字編輯器且將圖片上傳到伺服器的功能
阿新 • • 發佈:2021-01-15
一、準備工作
下載vue-quill-editor
npm install vue-quill-editor --save 或者 yarn add vue-quill-editor
二、定義全域性元件quill-editor
下載好vue-quill-editor後,我們需要定義一個全域性元件,把這個元件名字命名為quill-editor
1、定義template模板
<div> <quill-editor v-model="value" ref="myQuillEditor" :options="editorOption" @change="onEditorChange" > </quill-editor> <input type="file" hidden accept=".jpg,.png" ref="fileBtn" @change="handleChange" /> </div>
2、定義富文字選項配置
editorOption: { toolbar: [ ['bold','italic','underline'],//加粗、斜體、下劃線、刪除線,'strike' ['blockquote','code-block'],//引用、程式碼塊 [{ 'header': 1 },{ 'header': 2 }],//H1 H2 [{ 'list': 'ordered' },{ 'list': 'bullet' }],//列表 [{ 'script': 'sub' },{ 'script': 'super' }],//上標、下標 [{ 'indent': '-1' },{ 'indent': '+1' }],//縮排 [{ 'direction': 'rtl' }],//文字編輯方向,從左到右還是從右到左 [{ 'size': ['small',false,'large','huge'] }],//文字大小 [{ 'header': [1,2,3,4,5,6,false] }],//選中的文字容器高度 [{ 'font': [] }],//字型樣式 [{ 'color': [] },{ 'background': [] }],//顏色、背景顏色 [{ 'align': [] }],//對齊方式 ['clean'],//清除選中文字的所有樣式 ['link','image','video'] //超連結、圖片、視訊連結 ],}
三、相關方法
1、改變原有富文字編輯器上傳圖片繫結方法
mounted() { if (this.$refs.myQuillEditor) { //myQuillEditor改成自己的 this.$refs.myQuillEditor.quill.getModule("toolbar").addHandler("image",this.imgHandler); } },methods:{ imgHandler(state) { if (state) { //觸發input的單擊 ,fileBtn換成自己的 this.$refs.fileBtn.click() } } }
2、上傳事件
handleChange(e) { const files = Array.prototype.slice.call(e.target.files); if (!files) { return; } let formdata = new FormData(); formdata.append("file_name",files[0].name); formdata.append("imgs",files[0]); //使用了axios請求 this.axios({ url: this.$store.state.baseUrl + 'upload/ueditorFile',method: 'post',data: formdata,headers: {'client-identity': localStorage.getItem('session_id')} }).then((res) => { //這裡設定為空是為了聯絡上傳同張圖可以觸發change事件 this.$refs.fileBtn.value = ""; if (res.data.code == 200) { let selection = this.$refs.myQuillEditor.quill.getSelection(); //這裡就是返回的圖片地址,如果介面返回的不是可以訪問的地址,要自己拼接 let imgUrl = this.$store.state.baseUrl + res.data.data; imgUrl = imgUrl.replace(/\\/g,"/") //獲取quill的游標,插入圖片 this.$refs.myQuillEditor.quill.insertEmbed(selection != null ? selection.index : 0,imgUrl) //插入完成後,游標往後移動一位 this.$refs.myQuillEditor.quill.setSelection(selection.index + 1); } }) }
最後在父元件使用這個全域性quill元件,並傳遞自己需要的相關引數,就完成啦~
到此這篇關於vue使用vue-quill-editor富文字編輯器且將圖片上傳到伺服器的功能的文章就介紹到這了,更多相關vue-quill-editor上傳圖片到伺服器內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!