第一步 下载安装wangeditor
npm install @wangeditor/editor @wangeditor/editor-for-vue
第二步 项目里面新建组件,例如我在src/components文件夹新建 WangEditor文件夹新建index.vue 文件,文件内容如下:
<template>
<div class="editor-wrapper">
<!-- 工具栏 -->
<Toolbar
id="toolbar-container"
:editor="editorRef"
:default-config="toolbarConfig"
:mode="mode"
/>
<!-- 编辑器 -->
<Editor
id="editor-container"
v-model="modelValue"
:default-config="editorConfig"
:mode="mode"
@on-change="handleChange"
@on-created="handleCreated"
/>
</div>
</template>
<script setup lang="ts">
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
// API 引用
import FileAPI from "@/api/file";
const props = defineProps({
modelValue: {
type: [String],
default: "",
},
excludeKeys: {
type: Array<string>,
default: [],
}
});
const emit = defineEmits(["update:modelValue"]);
const modelValue = useVModel(props, "modelValue", emit);
const editorRef = shallowRef(); // 编辑器实例,必须用 shallowRef
const mode = ref("simple"); // 编辑器模式
const toolbarConfig = ref({
excludeKeys: props.excludeKeys,
}); // 工具条配置
// 编辑器配置
const editorConfig = ref({
placeholder: "请输入内容...",
MENU_CONF: {
uploadImage: {
// 自定义图片上传
async customUpload(file: any, insertFn: any) {
FileAPI.upload(file).then((data) => {
insertFn(data.url);
});
},
},
},
});
const handleCreated = (editor: any) => {
editorRef.value = editor; // 记录 editor 实例,重要!
};
function handleChange(editor: any) {
modelValue.value = editor.getHtml();
}
// 组件销毁时,也及时销毁编辑器
onBeforeUnmount(() => {
const editor = editorRef.value;
if (editor == null) return;
editor.destroy();
});
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
3、页面调用组件
<template>
<div class="add-details">
<div class="flex col-stretch">
<el-form-item label="商品详情" class="form-edit">
<WangEditor v-model="form.content" style="width:375px;height:718px;border:solid 1px #ddd;margin-right:10px;" :excludeKeys="excludeKeys" />
</el-form-item>
<div class="preview m-l-30 flex-none">
<div class="flex-1" style="min-height: 0">
<el-scrollbar class="ls-scrollbar" style="height: 100%">
<div class="p-l-10 p-r-10" v-html="form.content"></div>
</el-scrollbar>
</div>
</div>
</div>
</div>
</template>
<script lang="ts" setup>
const props = defineProps({
form: {
type: Object,
default:{},
}
});
const excludeKeys= ref([ "insertLink", "viewImageLink", "insertVideo", "emotion", "fullScreen","codeBlock","todo"])
</script>
我使用的是自动注册组件,所以页面不需要手动引用组件,如果没有自动注册组件,可以手动引用组件