Vue中使用QuillEditor富文本编辑器实现图片上传
你好! 这是我第一次使用 QuillEditor编辑器,与之搭配使用的是Element UI的el-upload组件。
1.安装
npm install vue-quill-editor –save
2.引用(可在main.js实现全局引用,亦可在当前页面按需引用)
import Vue from 'vue'
import VueQuillEditor from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
Vue.use(VueQuillEditor)
3.代码实现
(1)template标签中的html
<el-card style="height: 540px;">
<el-upload
class="avatar-uploader"
:headers="headerss"
:action="uploadAction"
:file-list="richImg"
:show-file-list="false"
:on-success="uploadSuccess"
:on-error="uploadError"
:before-upload="beforeUpload"
>
</el-upload>
<quill-editor ref="myQuillEditor" v-model="basicInfomation.introduce" :options="editorOption" style="height:340px;">
</quill-editor>
</el-card>
(2)script标签中的data中
data() {
return {
// html中引用的富文本
editorOption: {
placeholder: '',
theme: 'snow',
modules: {
toolbar: {
//toolbarOptions是富文本展示的功能
container: toolbarOptions,
// 监听图片上传点击事件
handlers: {
'image': function (value) {
if (value) {
// upload点击上传事件
document.querySelector('.avatar-uploader input').click()
} else {
this.quill.format('image', false)
}
}
}
}
}
},
basicInfomation: {
introduce: ''
},
// 请求头
headerss:{
token:localStorage.getItem('token'),
loginMark:localStorage.getItem('loginMark')
},
uploadAction: this.$api.module.fileUpload, // 图片上传的接口地址,引用方式各有不同
richImg: [] // 图片列表
}
}
(3)script标签内,与export default同级
const toolbarOptions = [
//可以自定义富文本有哪些功能
['bold', 'italic', 'underline', 'strike'],
[{ 'header': 1 }, { 'header': 2 }],
[{ 'list': 'ordered' }, { 'list': 'bullet' }],
[{ 'indent': '-1' }, { 'indent': '+1' }],
[{ 'direction': 'rtl' }],
[{ 'size': ['small', false, 'large', 'huge'] }],
[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
[{ 'color': [] }, { 'background': [] }],
[{ 'font': [] }],
[{ 'align': [] }],
['link', 'image'],
['clean']
]
(4)script标签内的methods方法
// 图片处理
uploadSuccess(res) {
console.log(res, 'res')
var dt = {}
dt.url = res.data
let quill = this.$refs.myQuillEditor.quill
console.log(quill)
// 如果上传成功
if (res.code === '0' && dt.url !== null) {
// 获取光标所在位置
let length = quill.getSelection().index
// 插入图片 dt.url为服务器返回的图片地址
quill.insertEmbed(length, 'image', this.$imgs + dt.url)
// 调整光标到最后
quill.setSelection(length + 1)
} else {
this.$message.error('图片插入失败')
}
// loading加载隐藏
this.quillUpdateImg = false
},
// 上传失败钩子函数
uploadError() {},
// 上传前钩子函数
beforeUpload() {}
最后,如果要回显在页面上只需要使用v-html就OK了。
因项目需求,通过多方查找资料与交流所得。如有侵权,请联系删除!