1 组件封装
<template><div class="editor-container"><div class="editor-wrapper"><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="handleCreated"@onChange="handleChange"/></div></div>
</template><script>
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
// 下载包
// npm install @wangeditor/editor-for-vue
// npm install @wangeditor/editor
// npm install @wangeditor/plugin-upload-attachment // 上传附件插件// npm install @wangeditor/editor@v5.1.23
// npm install @wangeditor/editor-for-vue@1.0.2export default {name: 'MyEditor',components: { Editor, Toolbar },data() {return {editor: null,html: '<p>请输入内容...</p>',toolbarConfig: {},editorConfig: {placeholder: '请输入内容...',MENU_CONF: {uploadImage: {server: '/api/upload', // 替换为您的图片上传接口fieldName: 'file',maxFileSize: 10 * 1024 * 1024, // 10MBmaxNumberOfFiles: 10,allowedFileTypes: ['image/*'],customInsert(res, insertFn) {// res 即服务端的返回结果// 从 res 中找到图片 url 并插入insertFn(res.url)},onError(file, err, res) {console.error(`${file.name} 上传出错`, err, res)}}}},mode: 'default'}},methods: {handleCreated(editor) {this.editor = Object.seal(editor)},handleChange(editor) {this.$emit('update:content', editor.getHtml())}},beforeDestroy() {const editor = this.editorif (editor == null) returneditor.destroy()}
}
</script><style scoped>
.editor-container {width: 100%;margin: 20px auto;text-align: left;
}.editor-wrapper {border: 1px solid #ccc;margin: 0 20px;
}:deep(.w-e-text-container) {text-align: left;
}
</style>
2 组件引入
<template><div class="wang-editor-page"><h2>WangEditor 富文本编辑器</h2><MyEditor @update:content="handleContentChange"/></div>
</template><script>
import MyEditor from '../components/MyEditor.vue'export default {name: 'WangEditor',components: {MyEditor},methods: {handleContentChange(content) {console.log('编辑器内容更新:', content)}}
}
</script><style scoped>
.wang-editor-page {padding: 20px;
}h2 {text-align: center;margin-bottom: 20px;
}
</style>