vue使用vue-quill-editor富文本编辑器且将图片上传到服务器的功能
一、准备工作
下载vue-quill-editor
npminstallvue-quill-editor--save或者yarnaddvue-quill-editor
二、定义全局组件quill-editor
下载好vue-quill-editor后,我们需要定义一个全局组件,把这个组件名字命名为quill-editor
1、定义template模板
2、定义富文本选项配置
editorOption:{
toolbar:[
['bold','italic','underline'],//加粗、斜体、下划线、删除线,'strike'
['blockquote','code-block'],//引用、代码块
[{'header':1},{'header':2}],//H1H2
[{'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){
constfiles=Array.prototype.slice.call(e.target.files);
if(!files){
return;
}
letformdata=newFormData();
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){
letselection=this.$refs.myQuillEditor.quill.getSelection();
//这里就是返回的图片地址,如果接口返回的不是可以访问的地址,要自己拼接
letimgUrl=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上传图片到服务器内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!