1:安装
npm install @wangeditor/editor @wangeditor/editor-for-vue --save
对应的两个版本^5.1.23 ^1.0.2
或
yarn add @wangeditor/editor @wangeditor/editor-for-vue
2:页面引入和使用
<templete>
<div>
<!-- 隐藏的文件上传 用于自定义富文本上传文件-->
<el-upload
v-if="1==2"
class="upload-demo1"
action="111"
:show-file-list="false"
:before-upload="handleChange1"
>
<el-button size="mini" type="primary"
>上传附件</el-button
>
</el-upload>
<div style="border: 1px solid #ccc;">
<!-- 工具栏 -->
<Toolbar
style="border-bottom: 1px solid #ccc"
:editor="editor"
:defaultConfig="toolbarConfig"
/>
<!-- 编辑器 -->
<Editor
style="height: 500px; overflow-y: hidden;"
:defaultConfig="editorConfig"
v-model="html"
@onCreated="onCreated"
/>
</div>
</div>
</templete>
<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
export default {
components: {Editor, Toolbar},
data(){
// 富文本
editor: null,
//富文本内容,传值给后端的会特别大,后端要有一个特别能装的类型
html: '',
toolbarConfig: {
//隐藏视频上传
excludeKeys: [
'insertVideo',
'uploadVideo',
'group-video'
]
},
editorConfig: {
placeholder: '请输入内容...',
MENU_CONF: {
async customBrowseAndUpload(resultFiles, insertImgFn) {
// 自定义上传按钮,点击上传的时候,触发隐藏按钮
document.querySelector('.upload-demo1 .el-upload__input').click()
},
},
},
},
methods: {
onCreated(editor) {
this.editor = Object.seal(editor) // 【注意】一定要用 Object.seal() 否则会报错
},
// 销毁富文本编辑器
destroyEdit() {
const editor = this.editor
if (editor == null) return
editor.destroy() // 组件销毁时,及时销毁 editor ,重要!!!
},
handleChange1(file) {
// 读取文件并转换为Base64 后端需要一个特别能装的类型,图片是base64的无需调取后端接口
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const base64String = reader.result;
const img = `<img src="${base64String}" alt="${file.name}"/>`;
// 上传成功后把图片插入内容
this.editor.dangerouslyInsertHtml(img);
};
},
},
}
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>