因为项目需要添加了vue-quill-editort富文本框,但是因为quill的图片上传是base64,这个保存在数据库不是很友好,查找资料后找到quill-image-extend-module插件,但是因为项目中使用了跨域的接口,在项目封装的直接接口请求,而在quill-image-extend-module插件始终不能请求返回数据的情况下,重新查找资料,直接用接口返回的图片地址。
说下思路:因为quill有开放很多的扩展和自定义方法,我们通过在mounted中获取自己的quill工具栏image,劫持image的handler方法,调用我们页面上一个隐藏的input:file上传文件。通过input的change方法去调用接口,获取返回的url
参考的资料 传送
各种引入就不说了
html部分
<quill-editor :options="editorOption" v-model="content"ref="myQuillEditor">
</quill-editor>
//隐藏的input
<input type="file" hidden accept=".jpg,.png" ref="fileBtn" @change="handleChange">
javacript
data(){
return {
editorOption: {
placeholder: '请输入信息详情',
}
}
}
mounted() {
if (this.$refs.myQuillEditor) {
//myQuillEditor改成自己的
this.$refs.myQuillEditor.quill.getModule("toolbar").addHandler("image", this.imgHandler);
//这里初始化,劫持toolbar的image的handler方法,在mounted中处理
}
}
methods: {
imgHandler(state) {
if (state) {
//触发input的单击 ,fileBtn换成自己的
this.$refs.fileBtn.click()
}
},
handleChange(e) {
const files = Array.prototype.slice.call(e.target.files);
if (!files) {
return;
}
let form = new FormData();
form.append("file", files[0]);
//使用了axios请求
axios({
url: 自己的服务接口,
method: 'post',
data: form,
headers: {'Content-Type': undefined},
withCredentials: true
}).then(({data: {responseData}}) => {
//这里设置为空是为了联系上传同张图可以触发change事件
this.$refs.fileBtn.value = "";
if (responseData.uploadSuccess) {
let selection = this.$refs.myQuillEditor.quill.getSelection();
//这里就是返回的图片地址,如果接口返回的不是可以访问的地址,要自己拼接
let imgUrl = responseData.imageUrl;
//获取quill的光标,插入图片
this.$refs.myQuillEditor.quill.insertEmbed(selection != null ? selection.index : 0, 'image', imgUrl)
//插入完成后,光标往后移动一位
this.$refs.myQuillEditor.quill.setSelection(selection.index + 1);
}
})
},
}