一、效果图
二、引入插件
需安装editor
yarn add @wangeditor/editor
yarn add @wangeditor/editor-for-vue
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { IToolbarConfig, IEditorConfig } from '@wangeditor/editor';
三、封装的组件代码
<template>
<div class="container">
<div style="border: 1px solid #ccc">
<Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
<Editor
style="height: 500px; overflow-y: hidden"
v-model="valueHtml"
:defaultConfig="editorConfig"
:mode="mode"
@onCreated="handleCreated"
/>
</div>
</div>
</template>
<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { IToolbarConfig, IEditorConfig } from '@wangeditor/editor';
// 编辑器实例,必须用 shallowRef
const editorRef = shallowRef();
const mode = ref('default');
// 内容 HTML
const valueHtml = ref();
const toolbarConfig: Partial<IToolbarConfig> = {};
const editorConfig: Partial<IEditorConfig> = {
placeholder: '请输入内容...',
MENU_CONF: {
uploadImage: {
async customUpload(file, insertFn) {
const formData = new FormData();
formData.append('multipartFile', file);
baseApi.singleFileUpload(formData).then(({ data }) => {
insertFn(data.filePath, '');
});
},
},
},
};
onMounted(() => {});
// 组件销毁时,也及时销毁编辑器
onBeforeUnmount(() => {
const editor = editorRef.value;
if (editor == null) return;
editor.destroy();
});
const handleCreated = (editor) => {
editorRef.value = editor; // 记录 editor 实例,重要!
};
</script>
四、其他补充
(一)工具栏配置
// 查看所有工具栏key
console.log(editor.getAllMenuKeys());
const toolbarConfig: Partial<IToolbarConfig> = {};
//去除某个工具
toolbarConfig.excludeKeys = ['group-video', 'fullScreen'];
(二)编辑器配置
// 编辑器配置
const editorConfig: Partial<IEditorConfig> = {
placeholder: '请输入内容...',
// 最长输入2000字
maxLength: 2000,
// 进入页面不自动聚焦
autoFocus: true,
MENU_CONF: {
},
};
(三)其他方法使用
1、@onChange="handleChange" 监听并获取文本内容
const handleChange = (editor: any) => {
console.log(editor.getHtml()) //获取带标签的全部内容
console.log(editor.getText()) //获取文本内容
};
2、v-loding 上传图片/视频 加载中动画
<Editor
class="editor"
v-model="createForm.noticeContext"
:defaultConfig="editorConfig"
:mode="mode"
v-loading="loading"
element-loading-text="加载中,请稍后..."
/>
效果如图: