WangEditor 是一款轻量级、开源、简洁的 Web 富文本编辑器,支持 HTML5 和现代浏览器,适合用于简单的内容编辑场景。本文将介绍如何在 Vue 2 项目中集成并使用 WangEditor,帮助你快速构建一个支持富文本编辑的应用。
一、项目初始化
首先,确保你已经安装了 Vue CLI,如果还未安装,可以通过以下命令全局安装:
npm install -g vue-cli
接着,使用 Vue CLI 初始化一个 Vue 2 项目:
vue init webpack my-vue-wangeditor-app
cd my-vue-wangeditor-app
npm install
启动开发服务器:
npm run dev
二、安装 WangEditor
接下来,在项目中安装 WangEditor:
npm install wangeditor --save
三、创建 WangEditor 组件
为了在 Vue 项目中使用 WangEditor,我们可以将其封装为一个 Vue 组件。
1. 创建 WangEditor 组件
在 src/components 文件夹中,创建一个名为 WangEditor.vue 的组件文件。
<template>
<div>
<div ref="editor" style="text-align: left;"></div>
</div>
</template>
<script>
import E from 'wangeditor';
export default {
name: 'WangEditor',
data() {
return {
editor: null, // WangEditor 实例
};
},
props: {
content: {
type: String,
default: ''
}
},
watch: {
// 当父组件传入的 content 变化时,更新编辑器内容
content(newContent) {
if (this.editor && newContent !== this.editor.txt.html()) {
this.editor.txt.html(newContent);
}
}
},
mounted() {
// 初始化 WangEditor
this.editor = new E(this.$refs.editor);
this.editor.config.onchange = () => {
// 编辑器内容变化时,触发 input 事件传递给父组件
this.$emit('input', this.editor.txt.html());
};
// 配置菜单和其他设置
this.editor.config.menus = [
'head', // 标题
'bold', // 粗体
'italic', // 斜体
'underline', // 下划线
'image', // 图片
'link', // 链接
'list', // 列表
'undo', // 撤销
'redo', // 重做
];
this.editor.config.zIndex = 1000;
// 创建编辑器
this.editor.create();
// 设置初始内容
if (this.content) {
this.editor.txt.html(this.content);
}
},
beforeDestroy() {
// 销毁编辑器实例,释放资源
if (this.editor) {
this.editor.destroy();
}
}
};
</script>
<style scoped>
/* 可以根据需要调整编辑器样式 */
</style>
2. 使用组件
在 src/App.vue 中引入并使用我们刚刚创建的 WangEditor 组件。
<template>
<div id="app">
<h1>WangEditor Demo</h1>
<WangEditor v-model="editorContent" />
<div>
<h2>实时预览</h2>
<div v-html="editorContent"></div>
</div>
</div>
</template>
<script>
import WangEditor from './components/WangEditor.vue';
export default {
name: 'App',
components: {
WangEditor
},
data() {
return {
editorContent: '<p>欢迎使用 WangEditor!</p>' // 初始化编辑器内容
};
}
};
</script>
<style>
/* 可根据需要添加全局样式 */
</style>
3. 运行效果
此时运行项目,npm run dev,你应该会看到 WangEditor 富文本编辑器出现在页面中,并且支持实时编辑和预览内容。
四、常见问题
1. 图片上传
WangEditor 支持图片上传功能,但默认是使用 base64 方式。你可以根据需要配置自己的图片上传服务。具体可以通过修改 editor.config.uploadImgServer 配置图片上传接口地址。
this.editor.config.uploadImgServer = '/api/upload'; // 图片上传接口
2. 自定义菜单栏
你可以通过 editor.config.menus 自定义显示哪些菜单栏。例如,移除不需要的菜单,只保留标题、加粗和图片:
this.editor.config.menus = [
'head',
'bold',
'image',
];
3. 禁用编辑功能
如果你需要将编辑器设置为只读模式,可以通过禁用菜单栏功能来实现:
this.editor.$textElem.attr('contenteditable', false); // 禁用编辑
五、总结
通过本文的步骤,你已经了解了如何在 Vue 2 项目中集成使用 WangEditor 富文本编辑器。从安装到使用的流程相对简单,并且 WangEditor 提供了丰富的扩展配置,能够满足大部分富文本编辑需求。你可以根据自己的项目需求,进一步配置上传功能或自定义菜单栏等功能。
希望这篇教程对你有所帮助,祝你在 Vue 项目开发中顺利使用 WangEditor!