文章标题:Vue组件实现富文本编辑器
文章摘要:本文介绍了如何使用Vue和Wangeditor插件实现富文本编辑器组件,并详细解释了组件中的各个部分和功能。
Vue组件实现富文本编辑器
在Web开发中,富文本编辑器是一个非常常见的功能,它能够让用户以所见即所得的方式编辑和排版文本内容。本文将介绍如何使用Vue和Wangeditor插件实现一个富文本编辑器组件。
- 安装依赖
首先,我们需要安装@wangeditor/editor-for-vue插件,该插件提供了与Vue集成的富文本编辑器组件。可以通过以下命令来安装:
bash
npm install @wangeditor/editor-for-vue
2. 创建富文本编辑器组件
在Vue项目中,创建一个名为RichTextEditor的组件,用于展示富文本编辑器界面和处理相关逻辑。
组件模板代码如下:
<template>
<div v-if="newVisible">
<div class="container"></div>
<div style="border: 1px solid #ccc">
<!-- 工具栏 -->
<Toolbar
:editor="editorRef"
style="border-bottom: 1px solid #ccc"
:defaultConfig="toolbarConfig"
/>
<!-- 编辑器 -->
<Editor
v-model="valueHtml"
:defaultConfig="editorConfig"
style="height: 500px; overflow-y: hidden"
@onCreated="handleCreated"
/>
</div>
<div class="btn-container">
<CBotton type="primary" @click="save">保存</CBotton>
<CBotton type="dashed" @click="cancel">取消</CBotton>
</div>
</div>
</template>
在上述代码中,我们通过v-if指令控制编辑器组件的显示和隐藏。组件包含一个工具栏和一个编辑器,并在底部添加了保存和取消按钮。
- 定义组件的数据和方法
在
<script setup>
import {
Editor, Toolbar } from "@wangeditor/editor-for-vue";
import {
uploadFile } from "@/api/base";
import {
submitUploadInfoApi, getHelpContent } from "@/api/sale/help-set.ts";
import {
message } from "ant-design-vue";
import {
onBeforeUnmount,
shallowRef,
defineProps,
ref,
computed,
defineEmits,
reactive,
watch,
} from "vue";
</script>
接着,定义组件需要的数据和方法:
javascript
// 编辑器实例,必须用 shallowRef,重要!
const editorRef = shallowRef();
const photoGalleryDialogVisible = ref();
const spinning = ref(false);
// 内容 HTML
const valueHtml = ref("");
const props = defineProps({
visible: {
type: Boolean, default: false },
info: {
type: Object, default: null },
content: {
type: Object, default: null },
});
const emit = defineEmits(<

最低0.47元/天 解锁文章
3675

被折叠的 条评论
为什么被折叠?



