|
最近做了一个文章上传的项目,因为考虑到文章内容中有文字样式的需求和图片的插入,就做了一个富文本框的功能,我选择的插件就是vue-quill-editor,下边总结一下我在这里边踩过的坑和解决方案。分为两大部分来讲解,使用和优化
一、使用
1,下载插件 npm install vue-quill-editor --save
2,引用
在vue的main.js文件中添加这两行代码,就是引用和使用
import QuillEditor from 'vue-quill-editor'
Vue.use(QuillEditor)
3,在插件中使用
(1)html部分
<el-form-item label="内容" :label-width="formLabelWidth"> <quill-editor v-model="content" ref="myQuillEditor" :options="editorOption" @blur="onEditorBlur($event)" @ focus="onEditorFocus($event)" @change="onEditorChange($event)"> </quill-editor> </el-form-item>
(2)editorOption这个数据是工具栏的定义(图片是便于观看,图片下边附部分你需要的代码)

工具栏功能的常量,我这个不全,网上随便找,有的是
const toolbarOptions = [ ['bold', 'italic', 'underline', 'strike'], // toggled buttons ['blockquote', 'code-block'], [{'list': 'ordered'}, {'list': 'bullet'}], [{'script': 'sub'}, {'script': 'super'}], // superscript/subscript [{'indent': '-1'}, {'indent': '+1'}], // outdent/indent [{'direction': 'rtl'}], // text direction [{'color': []}, {'background': []}], // dropdown with defaults from theme [{'align': []}], ['image'], ['clean'] // remove formatting button ]
工具栏的定义,与html中的数据变量是一致就行
editorOption: { placeholder: '', theme: 'snow', // or 'bubble' modules: { toolbar: { container: toolbarOptions, // 工具栏 } } }
4,内容处理
quill-editor 得到的内容是由若干个<p></p>标签包裹的字符串,我们可以根据需求自行处理
二、优化
在使用过程中,发现了一个问题,这个富文本编辑器对图片的处理是把图片转换成base-64格式的,小小的一张图片就是一组很长的字符串,如果内容中有过多的图片,那就会发生412错误,就是上传的数据量过大,面对这种情况服务器可以设置增大限制上线,但是这种方案就会显的很low,还会对回显有不利影响。我想办法做了优化,把富文本编辑器的图片导入功能直接做了上传,之后我们富文本的内容中直接就变成<p><img src="xxxxxxxx"></p>,这样子大大减少了内容对服务器的损耗。下边直接上代码,具体的功能请自行琢磨
html代码中增加一个上传的功能
<el-form-item label="内容"> <!-- 图片上传组件辅助--> <el-upload class="avatar-uploader quill-img" action="这里是你图片上传所访问的后台接口" :show-file-list="false" :on-success="uploadSuccess" > </el-upload> <!--富文本编辑器组件--> <quill-editor v-model="nowData.content" ref="myQuillEditor" :options="editorOption" @blur="onEditorBlur($event)" @focus="onEditorFocus($event)"@change="onEditorChange($event)"> </quill-editor> </el-form-item>
data中对image这项功能做重写覆盖
editorOption: { placeholder: '', theme: 'snow', // or 'bubble' modules: { toolbar: { container: toolbarOptions, // 工具栏 handlers: { 'image': function (value) { if (value) { // 触发input框选择图片文件 document.querySelector('.quill-img input').click() } else { this.quill.format('image', false); } } } } } }
methods中给上传成功的回调函数做处理
uploadSuccess(res) { //把已经上传的图片显示回富文本编辑框中
//res返回的格式是{url:"图片的路径"},这个是后台接口返回的 let quill = this.$refs.myQuillEditor.quill quill.focus(); quill.insertEmbed(quill.getSelection().index, 'image', res.url);
},
这回功能就做好了 |