核心主要是下面的这个代码
quill.insertEmbed(10, 'image', 'https://quilljs.com/images/cloud.png');
完整代码
<div ref="editorDom" class="editor"></div>
import Quill from 'quill';
import 'quill/dist/quill.bubble.css';
let editor = null;
// 页面加载完了在挂载实例
onMounted(() => {
editor = new Quill(editorDom.value, {
placeholder: '在此输入内容'
});
});
// 上传文件事件
function onImageFileChanged(params: any) {
const formdata = new FormData();
formdata.append('files', params.target.files[0]);
imageFileUpload.value.value = '';
uploadFile(formdata).then(res => {
console.log('res', res);
let imageData = res[0];
const { fileUrl } = imageData;
// 获取编辑器实例
const quill = editor;
// 设置编辑器焦点
quill.focus();
// 获取光标位置
const range = quill.getSelection();
if (range) {
// 插入图片
quill.insertEmbed(range.index, 'image', fileUrl);
// 设置光标位置在图片后面
quill.setSelection(range.index + 1);
if (range.length == 0) {
console.log('User cursor is at index', range.index);
} else {
var text = quill.getText(range.index, range.length);
console.log('User has highlighted: ', text);
}
} else {
console.log('User cursor is not in editor');
}
// 清空输入框
imageFileUpload.value.value = '';
});
}
其他方式
https://stackoverflow.com/questions/29008914/how-to-add-image-in-quill-js
编辑器自带
var editor = new Quill('#editorDiv',
{
modules: {
toolbar: [
...
['image'],
...
],
//not needed anymore: 'image-tooltip': true,
//not needed anymore: 'link-tooltip': true
...
},
...
});
自己写一个按钮,编辑器挂载
<div id="editorToolbarDiv">
...
<button class="ql-image"></button>
</div>
<div id="editorDiv"></div>
var editor = new Quill('#editorDiv',
{
modules: {
toolbar: '#editorToolbarDiv',
//not needed anymore: 'image-tooltip': true,
//not needed anymore: 'link-tooltip': true,
...
},
...
});
参考文章
这个写的特别好
其他参考
-
https://blog.csdn.net/weixin_42003972/article/details/105315167
-
https://codesandbox.io/examples/package/quill-image-uploader
-
https://codesandbox.io/s/vue-quill-uploader-forked-j129z3?file=/src/components/Article.vue:1025-1061
后记
还有个插件