最近在做后台管理平台,该项目是使用vue+element-ui框架,有一个界面就是关于消息推送的,在网上找了一圈,比较适合的就是vue-quill-editor富文本编辑器
1.需求完成图: 此项目就是给用户发送简单的消息和配上几张图片就行(比较简单), 也就是我发给后台的富文本内容中的图片是要先传到服务器中的 再观摩了一位大佬的网站: https://segmentfault.com/a/1190000012620431 我就跟着他后面写, 用了element中的upload上传图片
2.代码部分
<el-form-item prop="messageContent"> <el-col :span="1.5" > 正文: </el-col> <el-col style="width:800px" class="editor-col"> `在这里插入代码片` <el-card style="height: 400px;"> <!-- 图片上传组件辅助--> <el-upload class="avatar-uploader" :action="serverUrl" //上传到服务器的路径 name="file" :headers="header" :show-file-list="false" :on-success="uploadSuccess" :on-error="uploadError"> </el-upload> <quill-editor v-model="detailContent" style="height: 230px;" ref="myQuillEditor" :options="editorOption"> </quill-editor> </el-card> </el-col> </el-form-item>因为我只在这个界面用到, 所以不用封装成组件的,直接 npm install vue-quill-editor,在需要的页面引入就行
<script> import {quillEditor} from 'vue-quill-editor' import 'quill/dist/quill.core.css' import 'quill/dist/quill.snow.css' import 'quill/dist/quill.bubble.css' // 工具栏自定义配置-->我删除了几个板块,所以跟原本的会不一样 const toolbarOptions = [ ['bold', 'italic', 'underline'], // toggled buttons ['blockquote', 'code-block'], [{'header': 1}], // custom button values [{'list': 'ordered'}], [{'direction': 'rtl'}], // text direction [{'size': ['small', false, 'large', 'huge']}], // custom dropdown [{'header': [1, 2, 3, 4, 5, 6, false]}], [{'color': []}, {'background': []}], // dropdown with defaults from theme [{'font': []}], [{'align': []}], ['link', 'image', 'video'], ['clean'] // remove formatting button ] export default { name: 'FuncFormsEdit', components: { quillEditor }, data() { return { //后台将图片上传到服务器弄成接口了,我直接调用就行,你们可以用线上转图片试一下,我的api是配置好的, //就是www.xxxx.com serverUrl: '/api/file/uploadForApp', header: {token: sessionStorage.token}, detailContent:'', //富文本编辑器内容 editorOption: { placeholder: '', theme: 'snow', // or 'bubble' modules: { toolbar: { container: toolbarOptions, // 工具栏 handlers: { 'image': function (value) { if (value) { //****就是这里自定义了图片上传的事件**** //你们可以alert(1111)试下有没有成功 document.querySelector('.avatar-uploader input').click() } else { this.quill.format('image', false); } } } } } }, } }, methods:{ uploadSuccess(res, file) { console.log('图片上传到服务器',file.response.data.fileUrl) //res为图片服务器返回的数据 //获取富文本组件实例 let quill = this.$refs.myQuillEditor.quill console.log('uploadSuccess的res',res) // 如果上传成功 if (res.code == 0 && res.data !== null) { // 获取光标所在位置 let length = quill.getSelection().index; // 插入图片 res.info为服务器返回的图片地址 quill.insertEmbed(length, 'image', res.data.fileUrl) // 调整光标到最后 quill.setSelection(length + 1) } else { this.$message.error('uploadSuccess图片插入失败') } }, } } </script>然后表单提交的时候, 把富文本编辑器内容detailContent放进去就行
ps: 每次都写得啰里八嗦,望见谅,也是怕自己后期再来看的时候,看的云里雾里…>_<…