vue-quill-editor 在粘贴图片和选择图片上传的时候会自动转成base64格式,但是base64数据量太大不利于存储,我们可以将图片上传到服务器,然后存储一条链接更好
首先配置一下图片上传的事件:
editorOption: {
placeholder: '请输入内容',
modules:{
"emoji-toolbar": true,
"emoji-shortname": true,
toolbar: {
container: [],// toolbar工具栏的工具选项(默认展示全部) toolOptions:
},
clipboard:{
matchers:[
['img',this.handleCustomMatcher]
]
},
}
},
这个是配置的粘贴图片的事件
//将粘贴的图片替换为空
handleCustomMatcher(node,Delta){
console.log(node);
console.log(Delta);
let ops = [];
Delta.ops.forEach(op=>{
if(op.insert && typeof op.alt === 'string'){
ops.push({
insert:op.insert,
})
}
})
Delta.ops = ops
return Delta
},
在vue渲染完成之后,获取vue-quill,重置粘贴实践:
mounted() {
// 自定义粘贴图片功能
let quill = this.$refs.myQuillEditor.quill
let length = quill.selection.savedRange.index
quill.root.addEventListener('paste', evt => {
if (evt.clipboardData && evt.clipboardData.files && evt.clipboardData.files.length) {
evt.preventDefault();
[].forEach.call(evt.clipboardData.files, file => {
if (!file.type.match(/^image\/(gif|jpe?g|a?png|bmp)/i)) {
return
}
console.log(file);
var formdata=new FormData();
formdata.append("label_images",file);
const loading = this.$loading({
lock: true,
text: '图片加载中...',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)'
});
//我这里用了jq的ajax,可以用axios,
this.JQ.ajax({
url:'上传图片的接口',
type:'post',
data:formdata,
dataType:'json',
processData: false, // jQuery不要去处理发送的数据
contentType: false, // jQuery不要去设置Content-Type请求头
success:function(ret){
//.把图片插到光标的地方(第三个参数是图片的url)
quill.insertEmbed(length, 'image', 这里写接口回传的url)
//把光标移到图片的后面
quill.setSelection(length + 1);
loading.close();
},
error:function(error){
alert(error)
}
})
})
}
}, false);
},
这样自定义粘贴图片就完成了