这篇文章给大家介绍怎么在vue中利用vue-quill-editor富文本编辑器将图片上传到服务器,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
下载vue-quill-editor
npm install vue-quill-editor --save 或者 yarn add vue-quill-editor
下载好vue-quill-editor后,我们需要定义一个全局组件,把这个组件名字命名为quill-editor
<div>
<quill-editor
v-model="value"
ref="myQuillEditor"
:options="editorOption"
@change="onEditorChange"
>
</quill-editor>
<input type="file" hidden accept=".jpg,.png" ref="fileBtn" @change="handleChange" />
</div>
editorOption: {
toolbar: [
['bold', 'italic', 'underline'], //加粗、斜体、下划线、删除线, 'strike'
['blockquote', 'code-block'], //引用、代码块
[{ 'header': 1 }, { 'header': 2 }], //H1 H2
[{ 'list': 'ordered' }, { 'list': 'bullet' }], //列表
[{ 'script': 'sub' }, { 'script': 'super' }], //上标、下标
[{ 'indent': '-1' }, { 'indent': '+1' }], //缩进
[{ 'direction': 'rtl' }], //文字编辑方向,从左到右还是从右到左
[{ 'size': ['small', false, 'large', 'huge'] }], //文字大小
[{ 'header': [1, 2, 3, 4, 5, 6, false] }], //选中的文字容器高度
[{ 'font': [] }], //字体样式
[{ 'color': [] }, { 'background': [] }], //颜色、背景颜色
[{ 'align': [] }], //对齐方式
['clean'], //清除选中文字的所有样式
['link', 'image', 'video'] //超链接、图片、视频链接
],
}
mounted() {
if (this.$refs.myQuillEditor) {
//myQuillEditor改成自己的
this.$refs.myQuillEditor.quill.getModule("toolbar").addHandler("image", this.imgHandler);
}
},
methods:{
imgHandler(state) {
if (state) {
//触发input的单击 ,fileBtn换成自己的
this.$refs.fileBtn.click()
}
}
}
handleChange(e) {
const files = Array.prototype.slice.call(e.target.files);
if (!files) {
return;
}
let formdata = new FormData();
formdata.append("file_name", files[0].name);
formdata.append("imgs", files[0]);
//使用了axios请求
this.axios({
url: this.$store.state.baseUrl + 'upload/ueditorFile',
method: 'post',
data: formdata,
headers: {'client-identity': localStorage.getItem('session_id')}
}).then((res) => {
//这里设置为空是为了联系上传同张图可以触发change事件
this.$refs.fileBtn.value = "";
if (res.data.code == 200) {
let selection = this.$refs.myQuillEditor.quill.getSelection();
//这里就是返回的图片地址,如果接口返回的不是可以访问的地址,要自己拼接
let imgUrl = this.$store.state.baseUrl + res.data.data;
imgUrl = imgUrl.replace(/\\/g,"/")
//获取quill的光标,插入图片
this.$refs.myQuillEditor.quill.insertEmbed(selection != null ? selection.index : 0, 'image', imgUrl)
//插入完成后,光标往后移动一位
this.$refs.myQuillEditor.quill.setSelection(selection.index + 1);
}
})
}
关于怎么在vue中利用vue-quill-editor富文本编辑器将图片上传到服务器就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。