1.引入vue-quill-editor
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
2.vue-quill-editor工具栏自定义配置
const toolbarOptions = [
['bold', 'italic', 'underline'], // toggled buttons
['blockquote', 'code-block'],
[{'header': 1}], // custom button values
[{'list': 'ordered'}],
[{'direction': 'rtl'}], // text direction
[{'size': ['small', false, 'large', 'huge']}], // custom dropdown
[{'header': [1, 2, 3, 4, 5, 6, false]}],
[{'color': []}, {'background': []}], // dropdown with defaults from theme
[{'font': []}],
[{'align': []}],
['link', 'image', 'video'],
['clean'] // remove formatting button
]
3.html引入
<el-upload
v-loading="loading"
class="avatar-uploader"
:action="serverUrl"
:headers="header"
name="image"
:show-file-list="false"
:http-request="uploadImg"
>
</el-upload>
<quill-editor v-model="content" ref="myQuillEditor" :options="editorOption" @change="onEditorChange($event)">
</quill-editor>
4.基础配置
content: null,
quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画,刚开始是false,不显示
editorOption: {
theme: "snow", // or 'bubble'
placeholder: "请输入标题内容",
modules: {
toolbar: {
container: toolbarOptions, // 工具栏
handlers: {
'image': function (value) {
if (value) {
//****就是这里自定义了图片上传的事件****
document.querySelector('.avatar-uploader input').click()
} else {
this.quill.format('image', false);
}
}
}
}
}
},
serverUrl: this.$store.state.login.appip+"/question/uploadImage", // 这里写你要上传的图片服务器地址
header: {header_token: localStorage.getItem('rootToken')},
imgUrl:'',
loading: false,
fileReader: '',
5.使用方法
onEditorChange(e) {
console.log('编辑器内容',this.content)
//this.$refs["myQuillEditor"].getContents()
},
uploadImg(options){
console.log(options)
let that = this;
var reader = new FileReader();
reader.readAsDataURL(options.file);
reader.onload = function(e){
that.imgUrl = this.result;
that.uploadImgs();
}
console.log('需上传',this.imgUrl);
},
uploadImgs(){
this.loading = true;
let that = this;
let data = Qs.stringify({
image: this.imgUrl
});
axios({
method:'post',
url:this.$store.state.login.inaddress+'/question/uploadImage',
data: data,
headers:{header_token: localStorage.getItem('rootToken')}
})
.then(function(res){
console.log(res);
//res为图片服务器返回的数据
//获取富文本组件实例
let quill = that.$refs.myQuillEditor.quill
// 如果上传成功
if (res.data.code == 200 && res.data.message == '请求成功') {
// 获取光标所在位置
let length = quill.getSelection().index;
// 插入图片res.data.content.imageUrl为服务器返回的图片地址
quill.insertEmbed(length, 'image', res.data.content.imageUrl)
// 调整光标到最后
quill.setSelection(length + 1)
} else {
that.$message.error('图片插入失败')
}
that.loading = false;
})
.catch(function(error){
that.loading = false;
console.log(error)
})
},