<template>
<div :ref="editorRef" @input="result"></div>
</template>
<script>
import E from 'wangeditor'
export default {
getters: ['qiniuHost'],
actions: ['getQiniuToken', 'uploadFile'],
props: {
editorRef: {
type: String,
default: 'wangeditor'
},
content: {
default: ''
}
},
data () {
return {
editor: null,
token: ''
}
},
async mounted () {
this.initEditor()
},
watch: {
content (v) {
this.editor.txt.html(v)
}
},
methods: {
result () {
this.$emit('input', this.editor.txt.html())
},
// 上传图片
upload (blob, url) {
/* global FormData */
return this.getQiniuToken().then(res => {
let form = new FormData()
form.append('file', blob)
form.append('token', res.token)
/* global fetch */
return fetch(url, {
method: 'POST',
body: form,
cache: 'no-cache',
processData: false,
forceSync: false,
contentType: 'multipart/form-data'
})
.then(response => response.json())
.catch(error => console.error('Error:', error))
})
},
// 遍历对象
objForEach (obj, fn) {
var key = void 0,
result = void 0
for (key in obj) {
if (obj.hasOwnProperty(key)) {
result = fn.call(obj, key, obj[key])
if (result === false) {
break
}
}
}
},
async initEditor () {
const editor = new E(this.$refs[this.editorRef])
editor.customConfig = {
showLinkImg: false, // 隐藏“网络图片”tab
dragdrop: true,
uploadImgHooks: {
fail: function (xhr, editor, result) {
// 图片上传并返回结果,但图片插入错误时触发
// xhr 是 XMLHttpRequst 对象,editor 是编辑器对象,result 是服务器端返回的结果
}
}
}
editor.customConfig.customUploadImg = (files, insert) => {
const uploadFile = (filesArr) => {
if (filesArr.length > 0) {
this.upload(filesArr.shift(), '服务器地址').then(res => {
if (res.key) {
const imgUrl = this.qiniuHost + res.key
insert(imgUrl)
uploadFile(filesArr)
}
})
}
}
uploadFile(files)
}
// 将图片大小限制为 3M
editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024
// 限制一次最多上传 5 张图片
editor.customConfig.uploadImgMaxLength = 30
editor.create()
this.editor = editor
const IDS = document.getElementById(this.editor.textElemId)
IDS.addEventListener('paste', (e) => {
const result = []
const clipboardData = e.clipboardData || e.originalEvent && e.originalEvent.clipboardData || {}
const items = clipboardData.items
this.objForEach(items, function (key, value) {
var type = value.type
if (/image/i.test(type)) {
result.push(value.getAsFile())
}
})
this.upload(result.shift(), '服务器地址').then(res => {
if (res.key) {
const imgUrl = this.qiniuHost + res.key
editor.cmd.do('insertHtml', '<img src="' + imgUrl + '" style="max-width:100%;"/>')
}
})
})
}
}
}
</script>