您的位置:首页技术文章
文章详情页

vue使用vue-quill-editor富文本编辑器且将图片上传到服务器的功能

【字号: 日期:2022-10-11 10:54:51浏览:3作者:猪猪
一、准备工作

下载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, ’image’, imgUrl) //插入完成后,光标往后移动一位 this.$refs.myQuillEditor.quill.setSelection(selection.index + 1); } })}

最后在父组件使用这个全局quill组件,并传递自己需要的相关参数,就完成啦~

到此这篇关于vue使用vue-quill-editor富文本编辑器且将图片上传到服务器的功能的文章就介绍到这了,更多相关vue-quill-editor上传图片到服务器内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!

标签: Vue
相关文章: