vue使用vue-quill-editor富文本編輯器且將圖片上傳到服務器的功能
更新時間:2021年01月13日 09:14:57 作者:輕嘆年華逝,
這篇文章主要介紹了vue使用vue-quill-editor富文本編輯器且將圖片上傳到服務器的功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
一、準備工作
下載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) {
//觸發(fā)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) => {
//這里設置為空是為了聯(lián)系上傳同張圖可以觸發(fā)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, 'image', imgUrl)
//插入完成后,光標往后移動一位
this.$refs.myQuillEditor.quill.setSelection(selection.index + 1);
}
})
}
最后在父組件使用這個全局quill組件,并傳遞自己需要的相關參數,就完成啦~
到此這篇關于vue使用vue-quill-editor富文本編輯器且將圖片上傳到服務器的功能的文章就介紹到這了,更多相關vue-quill-editor上傳圖片到服務器內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

