资料
Vue2.0 版本的安装:https://www.wangeditor.com/v5/for-frame.html#%E4%BD%BF%E7%94%A8 上传图片配置:https://www.wangeditor.com/v5/menu-config.html#%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87
安装步骤
1.安装界面基础部分
<!-- 富文本编辑器 -->
<template><div class="WangEditor" style="border: 1px solid #ccc"><Toolbarstyle="border-bottom: 1px solid #ccc":editor="editor":defaultConfig="toolbarConfig":mode="mode"/><Editorstyle="height: 500px; overflow-y: hidden;"v-model="html":defaultConfig="editorConfig":mode="mode"@onCreated="onCreated"/></div>
</template><script>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'export default {components: { Editor, Toolbar },data() {return {editor: null,html: '<p>hello</p>',toolbarConfig: {},editorConfig: { placeholder: '请输入内容...',},mode: 'default', // or 'simple'}},mounted() {// 模拟 ajax 请求,异步渲染编辑器setTimeout(() => {this.html = '<p>模拟 Ajax 异步设置内容 HTML</p>'}, 1500)},beforeDestroy() {const editor = this.editorif (editor == null) returneditor.destroy() // 组件销毁时,及时销毁编辑器},methods: {// 编辑器实例创建完毕后回调onCreated(editor) {// 对象密封this.editor = Object.seal(editor) // 一定要用 Object.seal() ,否则会报错},},}
</script><style scoped lang="scss">
.WangEditor{// 去掉重影小叉::v-deep .btn-close {svg {display: none;}}
}
</style>
2.配置上传服务
editorConfig : { placeholder : '请输入内容...' , MENU_CONF : { uploadImage : { fieldName : 'images' , server : 'http://localhost:3000/api/uploadImage' , maxSize : 5 * 1024 * 1024 , } }
} ,
3.搭建后端Api
3-1. 设置静态文件,添加目录
const app = express ( ) ;
app. use ( '/uploads' , express. static ( path. join ( __dirname, 'public' , 'uploads' ) ) ) ;
3-2. 配置Multer
const storage = multer. diskStorage ( { destination : ( req, file, cb ) => { cb ( null , 'public/uploads/' ) ; } , filename : ( req, file, cb ) => { const sanitizedFilename = Date. now ( ) + '-' + encodeURIComponent ( file. originalname) ; cb ( null , sanitizedFilename) ; }
} ) ;
const upload = multer ( { storage : storage, limits : { fileSize : 5 * 1024 * 1024 } ,
} ) . single ( 'images' ) ;
3-3. 配置图片上传api
app. post ( '/api/uploadImage' , ( req, res ) => { upload ( req, res, ( err ) => { if ( err) { return res. status ( 500 ) . json ( { errno : 1 , message : '文件上传失败' , } ) ; } const file = req. file; if ( ! file) { return res. status ( 400 ) . json ( { errno : 1 , message : '没有上传文件' , } ) ; } const ip = req. socket. localAddress === '::1' ? 'localhost' : req. socket. localAddress; const port = 3000 ; const baseUrl = ` http:// ${ ip} : ${ port} /uploads/ ` ; res. status ( 200 ) . json ( { errno : 0 , data : { url : ` ${ baseUrl} ${ file. filename} ` , alt : 'Uploaded Image' , href : '' , } , } ) ; } )
} )
4.解决弹窗小叉重影
<style scoped lang="scss">
.WangEditor { // 去掉重影小叉::v-deep .btn-close { svg { display : none; } }
}
</style>