首先使用组件
<quill-editor style="width: 700px;height: 200px" v-model="editFields.details" disabled
:options="editorOption"></quill-editor>
import {quillEditor} from 'vue-quill-editor'
data() {
return {
//富文本编辑
editorOption: {
// 配置富文本编辑器
},}
}
然后把富文本编辑器的选择图片按钮替换为上传到服务器,不做这个的话,默认图片是base64,富文本会非常大
methods: {
/*------------------------富文本编辑器的图片替换为上传到服务器--------------------------*/
handleImageClick() {
// 执行文件选择操作
const input = document.createElement('input');
input.type = 'file';
input.accept = 'image/*';
input.onchange = (event) => this.handleFileChange(event);
input.click();
},
handleFileChange(event) {
const file = event.target.files[0];
const formData = new FormData();
formData.append('file', file);
// 执行上传文件的请求,将图片上传到服务器
this.$http.post(this.$requrl.requestUrl + '/system/uploadImg', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(res => {
console.log(res);
if (res.data.code === '000000') {
this.$message.success('上传成功!');
console.log(res.data.data);
// 将图片插入富文本编辑器
const quill = this.$refs.editor.quill;
const range = quill.getSelection();
quill.clipboard.dangerouslyPasteHTML(range.index, `<img src="${this.$requrl.imgpath +res.data.data}">`);
} else {
this.$message.error('上传失败!');
}
}).catch(error => {
console.log(error);
});
},
}
这里是在显示富文本编辑器之前的方法里面,如果页面一打开就有富文本编辑器,可以写在mounted里面,我这里是在新增弹框里面,所以写在新增弹窗弹出之后了
// 处理新增操作
handleAdd() {
this.$nextTick(() => {//需要等待组件渲染完成再获取
const quill = this.$refs.editor.quill;
// 获取工具栏模块
const toolbar = quill.getModule('toolbar');
// 监听图片按钮的点击事件
toolbar.addHandler('image', this.handleImageClick);
});
},