使用wangeditor编辑器 wangEditor
下载依赖
npm install @wangeditor/editor-for-vue
npm install @wangeditor/editor
引入依赖并注册
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
components: { Editor, Toolbar },
准备初始数据
<template>
<div style="border: 1px solid #ccc">
<Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig" :mode="mode" />
<Editor style="height: 500px; overflow-y: hidden" v-model="html" :defaultConfig="editorConfig" :mode="mode"
@onCreated="onCreated" />
</div>
</template>
data() {
return {
editor: null,
html: "",
toolbarConfig: {
excludeKeys: "fullScreen", // 排除全屏
},
editorConfig: { placeholder: "请输入内容..." },
mode: "default", // or 'simple',
// toolbarConfig: {
// menus: [
// 'head',
// 'italic',
// 'underline',
// 'strikeThrough',
// 'foreColor',
// 'backColor',
// 'link',
// 'list',
// 'justify',
// 'quote',
// 'emoticon',
// 'image',
// 'video',
// 'table',
// 'code',
// 'undo',
// 'redo'
// ],
// config: {
// uploadImgServer: '/upload', // 图片上传地址
// uploadFileName: 'file', // 文件域名字
// uploadImgMaxSize: 5 * 1024 * 1024, // 5M
// uploadImgMaxLength: 5, // 一次最多上传 5 张图片
// uploadImgParams: {}, // 其他参数
// uploadImgHeaders: {}, // 设置 header
// uploadImgHooks: {
// before(xhr, editor, files) {
// // 图片上传之前触发
// // xhr 是 XMLHttpRequest 对象,editor 是编辑器对象,files 是选择的图片文件
// },
// success(xhr, editor, result) {
// // 图片上传并返回结果,图片插入成功触发
// // xhr 是 XMLHttpRequest 对象,editor 是编辑器对象,result 是服务器端返回的结果
// },
// fail(xhr, editor, result) {
// // 图片上传并返回结果,但图片插入错误触发
// // xhr 是 XMLHttpRequest 对象,editor 是编辑器对象,result 是服务器端返回的结果
// },
// error(xhr, editor) {
// // 图片上传出错触发
// // xhr 是 XMLHttpRequest 对象,editor 是编辑器对象
// },
// timeout(xhr, editor) {
// // 图片上传超时触发
// // xhr 是 XMLHttpRequest 对象,editor 是编辑器对象
// },
// customInsert(insertImg, result, editor) {
// // 自定义图片插入方式
// // insertImg 是插入图片的函数,editor 是编辑器对象,result 是服务器端返回的结果
// const url = result.data.url // 获取图片 URL
// insertImg(url) // 插入图片到编辑器中
// }
// }
// }
// }
}
}
mounted() {
if (this.$route.query?.enableFlag) {
this.value1 = this.$route.query.enableFlag === 0 ? true : false
}
if (this.$route.query?.id) {
getArticleByIdAPI({ id: this.$route.query.id }).then((res) => {
if (res.code === 200) {
this.title = res.data.title;
this.html = res.data.htmlContent;
}
});
}
// 模拟 ajax 请求,异步渲染编辑器
// setTimeout(() => {
// this.html = '<p>模拟 Ajax 异步设置内容 HTML</p>'
// }, 1500)
}
methods: {
onCreated(editor) {
this.editor = Object.seal(editor); // 一定要用 Object.seal() ,否则会报错
},
}
beforeDestroy() {
const editor = this.editor;
if (editor == null) return;
editor.destroy(); // 组件销毁时,及时销毁编辑器
},