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)
})
},