May 30, 2021 Article blog
1. 1, define the template template
2. 2, define rich text options configuration
3. 1, change the original rich text editor upload picture binding method
Download vue-quill-editor
npm install vue-quill-editor --save 或者 yarn add vue-quill-editor
After downloading vue-quill-editor, we need to define a global component and name it 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);
}
})
}
Finally, when the parent component uses this global quill component and passes the relevant parameters it needs, it is done
Recommended lessons: Vue .js three-day hands-on tutorial, Vue 3.0 new features comprehensive analysis