开发了一个通知公告的功能,需要使用富文本编辑器,富文本编辑器上传图片时,src保存的时候base64格式,跟后端沟通了一下,先是把图片上传到服务器再把src绑定给图片。
安装
npm install @wangeditor/editor --save
npm install @wangeditor/editor-for-vue --save
使用
项目使用nuxt,要服务端渲染,而服务端没有window会报错。
<el-form-item
prop="content"
label="公告内容"
:label-width="formLabelWidth"
>
<div style="border: 1px solid #e8ecf0">
<component
:is="toolBarComponent"
style="border-bottom: 1px solid #ccc"
:mode="mode"
:editor="editor"
:default-config="toolbarConfig"
></component>
<component
:is="editorComponent"
v-model="formData.content"
style="height: 300px; overflow-y: hidden"
:default-config="editorConfig"
:mode="mode"
@onCreated="onCreated"
></component>
</div>
</el-form-item>
核心代码
import tool from '@/utils/tools.js'
import '@wangeditor/editor/dist/css/style.css'
export default {
data() {
return {
editor: null,
toolbarConfig: {},
editorConfig: { MENU_CONF: {} },
mode: 'default', // or 'simple'
toolBarComponent: null, // 工具栏
editorComponent: null, // 编辑组件
}
},
created() {
if (process.client) {
const editor = require('@wangeditor/editor-for-vue')
this.editorComponent = editor.Editor
this.toolBarComponent = editor.Toolbar
let that = this
// 自定义上传图片
that.editorConfig.MENU_CONF['uploadImage'] = {
customUpload(file, insertFn) {
const fileName = file.name
const m = fileName.match(/\.(\w+)(#|\?|$)/)
const fileType = (m && m[1]).toString().toLowerCase()
const allowHook = ['jpg', 'jpeg', 'png']
const validType = (allowHook).includes(fileType)
if (!validType) {
that.$message.error('只支持图片类型文件上传')
return false
}
if (fileName.indexOf('%') > -1 || fileName.indexOf('&') > -1) {
that.$message.error('上传文件名称不能带有字符"%","&"')
return false
}
const isLt5M = file.size / 1024 / 1024 < 5
if (!isLt5M) {
that.$message.error('上传图片大小不能超过 5MB!')
return false
}
if (['jpg', 'jpeg', 'png'].includes(fileType)) {
return new Promise((resolve, reject) => {
tool.compress(file, async (newfileex) => {
// console.log('newFile', newfileex)
resolve(newfileex)
// 压缩之后的图片上传 后端接口
let fileUrl = await getFileUrl(newfileex)
// 自己实现上传,并得到图片 url alt href
let url = `${that.$fileServerUrl}/${fileUrl}`
let alt = file.name
let href = url
// 最后插入图片
insertFn(url, alt, href)
})
})
}
}
}
}
},
beforeDestroy() {
const editor = this.editor
if (editor == null) return
editor.destroy() // 组件销毁时,及时销毁编辑器
},
methods: {
onCreated(editor) {
this.editor = Object.seal(editor) // 一定要用 Object.seal() ,否则会报错
},
}
}
tools.js 上传图片之前做了压缩,可以参考这里