在Vue中使用wangeditor创建富文本编辑器的完整指南

🌟 前言

欢迎来到我的技术小宇宙!🌌 这里不仅是我记录技术点滴的后花园,也是我分享学习心得和项目经验的乐园。📚 无论你是技术小白还是资深大牛,这里总有一些内容能触动你的好奇心。🔍

在这里插入图片描述

在Vue中使用wangeditor创建富文本编辑器的完整指南

效果图

wangeditor 官网指南

在这里插入图片描述

在Vue项目中使用wangeditor构建富文本编辑器,您需要遵循以下步骤来集成和使用这个流行的编辑器:

步骤 1: 安装 wangeditor

首先,您需要在Vue项目中安装wangeditor。可以通过npm来完成安装:

yarn add @wangeditor/editor
# 或者 npm install @wangeditor/editor --save

yarn add @wangeditor/editor-for-vue@next
# 或者 npm install @wangeditor/editor-for-vue@next --save

步骤 2: 引入 wangeditor 到您的组件

在您希望使用富文本编辑器的Vue组件中,引入wangeditor

import '@wangeditor/editor/dist/css/style.css';// 引入编辑器的CSS样式
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';

步骤 3: 创建编辑器实例和响应式数据

在Vue组件的mounted生命周期钩子中,创建wangeditor的实例,并将其绑定到指定的DOM元素上:

export default {
  components: { Editor, Toolbar },
  setup() {
    // 编辑器实例,必须用 shallowRef,重要!
    const editorRef = shallowRef();

    // 内容 HTML
    const valueHtml = ref('<p>hello</p>');

    // 模拟 ajax 异步获取内容
    onMounted(() => {
      setTimeout(() => {
        valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>';
      }, 1500);
    });

    const toolbarConfig = {};
    const editorConfig = { placeholder: '请输入内容...' };

    // 组件销毁时,也及时销毁编辑器,重要!
    onBeforeUnmount(() => {
      const editor = editorRef.value;
      if (editor == null) return;

      editor.destroy();
    });

    // 编辑器回调函数
    const handleCreated = (editor) => {
      console.log('created', editor);
      editorRef.value = editor; // 记录 editor 实例,重要!
    };
    const handleChange = (editor) => {
      console.log('change:', editor.getHtml());
    };
    const handleDestroyed = (editor) => {
      console.log('destroyed', editor);
    };
    const handleFocus = (editor) => {
      console.log('focus', editor);
    };
    const handleBlur = (editor) => {
      console.log('blur', editor);
    };
    const customAlert = (info, type) => {
      alert(`【自定义提示】${type} - ${info}`);
    };
    const customPaste = (editor, event, callback) => {
      console.log('ClipboardEvent 粘贴事件对象', event);

      // 自定义插入内容
      editor.insertText('xxx');

      // 返回值(注意,vue 事件的返回值,不能用 return)
      callback(false); // 返回 false ,阻止默认粘贴行为
      // callback(true) // 返回 true ,继续默认的粘贴行为
    };

    const insertText = () => {
      const editor = editorRef.value;
      if (editor == null) return;

      editor.insertText('hello world');
    };

    const printHtml = () => {
      const editor = editorRef.value;
      if (editor == null) return;
      console.log(editor.getHtml());
    };

    const disable = () => {
      const editor = editorRef.value;
      if (editor == null) return;
      editor.disable()
    };

    return {
      editorRef,
      mode: 'default',
      valueHtml,
      toolbarConfig,
      editorConfig,
      handleCreated,
      handleChange,
      handleDestroyed,
      handleFocus,
      handleBlur,
      customAlert,
      customPaste,
      insertText,
      printHtml,
      disable
    };
  },
};

步骤 4: 在模板中添加编辑器容器

在Vue组件的模板中,添加一个容器元素来承载wangeditor

    <div style="border: 1px solid #ccc; margin-top: 10px">
      <Toolbar
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
        style="border-bottom: 1px solid #ccc"
      />
      <Editor
        :defaultConfig="editorConfig"
        :mode="mode"
        v-model="valueHtml"
        style="height: 400px; overflow-y: hidden"
        @onCreated="handleCreated"
        @onChange="handleChange"
        @onDestroyed="handleDestroyed"
        @onFocus="handleFocus"
        @onBlur="handleBlur"
        @customAlert="customAlert"
        @customPaste="customPaste"
      />
    </div>

步骤 5: 配置 wangeditor(可选)

wangeditor提供了多种配置选项,您可以根据需要进行配置。例如,设置编辑器的自定义菜单、上传图片的接口等:

// const editorConfig = { placeholder: '请输入内容...' };
    // 初始化 MENU_CONF 属性
    const editorConfig = {                       // JS 语法
      MENU_CONF: {},
      placeholder: '请输入内容...'
      // 其他属性...
    }

    // 修改 uploadImage 菜单配置
    editorConfig.MENU_CONF['uploadImage'] = {
      server: '/api/upload-image',
      fieldName: 'custom-field-name'
      // 继续写其他配置...

      //【注意】不需要修改的不用写,wangEditor 会去 merge 当前其他配置
    }

在这里插入图片描述

步骤 6: 获取编辑器内容(可选)

您可以通过editor.txt.html()方法获取编辑器的HTML内容,或者通过editor.txt.text()获取纯文本内容:

    const printHtml = () => {
      const editor = editorRef.value;
      if (editor == null) return;
      console.log(editor.getHtml());
    };

步骤 7: 清理资源

当组件销毁时,确保释放编辑器资源,避免内存泄漏:

    // 组件销毁时,也及时销毁编辑器,重要!
    onBeforeUnmount(() => {
      const editor = editorRef.value;
      if (editor == null) return;

      editor.destroy();
    });

全部代码

<template>
  <div>
    <div>
      <button @click="insertText">insert text</button>
      <button @click="printHtml">print html</button>
      <button @click="disable">disable</button>
    </div>
    <div style="border: 1px solid #ccc; margin-top: 10px">
      <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" style="border-bottom: 1px solid #ccc" />
      <Editor :defaultConfig="editorConfig" :mode="mode" v-model="valueHtml" style="height: 400px; overflow-y: hidden"
        @onCreated="handleCreated" @onChange="handleChange" @onDestroyed="handleDestroyed" @onFocus="handleFocus"
        @onBlur="handleBlur" @customAlert="customAlert" @customPaste="customPaste" />
    </div>
    <div style="margin-top: 10px">
      <textarea v-model="valueHtml" readonly style="width: 100%; height: 200px; outline: none"></textarea>
    </div>
  </div>
</template>

<script>
import '@wangeditor/editor/dist/css/style.css';
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';

export default {
  components: { Editor, Toolbar },
  setup() {
    // 编辑器实例,必须用 shallowRef,重要!
    const editorRef = shallowRef();

    // 内容 HTML
    const valueHtml = ref('<p>hello</p>');

    // 模拟 ajax 异步获取内容
    onMounted(() => {
      setTimeout(() => {
        valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>';
      }, 1500);
    });

    const toolbarConfig = {};
    // const editorConfig = { placeholder: '请输入内容...' };
    // 初始化 MENU_CONF 属性
    const editorConfig = {                       // JS 语法
      MENU_CONF: {},
      placeholder: '请输入内容...'
      // 其他属性...
    }

    // 修改 uploadImage 菜单配置
    editorConfig.MENU_CONF['uploadImage'] = {
      server: '/api/upload-image',
      fieldName: 'custom-field-name'
      // 继续写其他配置...

      //【注意】不需要修改的不用写,wangEditor 会去 merge 当前其他配置
    }


    // 组件销毁时,也及时销毁编辑器,重要!
    onBeforeUnmount(() => {
      const editor = editorRef.value;
      if (editor == null) return;

      editor.destroy();
    });

    // 编辑器回调函数
    const handleCreated = (editor) => {
      console.log('created', editor);
      editorRef.value = editor; // 记录 editor 实例,重要!
    };
    const handleChange = (editor) => {
      console.log('change:', editor.getHtml());
    };
    const handleDestroyed = (editor) => {
      console.log('destroyed', editor);
    };
    const handleFocus = (editor) => {
      console.log('focus', editor);
    };
    const handleBlur = (editor) => {
      console.log('blur', editor);
    };
    const customAlert = (info, type) => {
      alert(`【自定义提示】${type} - ${info}`);
    };
    const customPaste = (editor, event, callback) => {
      console.log('ClipboardEvent 粘贴事件对象', event);

      // 自定义插入内容
      editor.insertText('xxx');

      // 返回值(注意,vue 事件的返回值,不能用 return)
      callback(false); // 返回 false ,阻止默认粘贴行为
      // callback(true) // 返回 true ,继续默认的粘贴行为
    };

    const insertText = () => {
      const editor = editorRef.value;
      if (editor == null) return;

      editor.insertText('hello world');
    };

    const printHtml = () => {
      const editor = editorRef.value;
      if (editor == null) return;
      console.log(editor.getHtml());
    };

    const disable = () => {
      const editor = editorRef.value;
      if (editor == null) return;
      editor.disable()
    };

    return {
      editorRef,
      mode: 'default',
      valueHtml,
      toolbarConfig,
      editorConfig,
      handleCreated,
      handleChange,
      handleDestroyed,
      handleFocus,
      handleBlur,
      customAlert,
      customPaste,
      insertText,
      printHtml,
      disable
    };
  },
};
</script>

通过以上步骤,您可以在Vue项目中轻松地集成和使用wangeditor作为富文本编辑器。wangeditor提供了丰富的功能和良好的定制性,可以满足大多数富文本编辑的需求。

🎉 往期精彩回顾

Vue项目中使用ECharts构建交互式中国地图的详细指南

  • 598阅读 · 12点赞 · 6收藏

米哈游一面前端开发岗面试题,你会做几道?

  • 887阅读 · 21点赞 · 15收藏

程序员必备开发工具、程序员必备集成开发环境(IDE)

  • 635阅读 · 14点赞 · 8收藏

Linux常用操作命令和服务器硬件基础知识

  • 841阅读 · 28点赞 · 9收藏

C语言中大小写字母如何转化

  • 681阅读 · 25点赞 · 27收藏

主流开发语言和开发环境、程序员如何选择职业赛道?

  • 1015阅读 · 34点赞 · 16收藏

Spring Boot+Vue前后端分离项目如何部署到服务器

  • 1048阅读 · 30点赞 · 25收藏

Spring Cloud原理详解、Spring Cloud发展历程

  • 1036阅读 · 32点赞 · 9收藏

爬虫基本原理介绍、实现及问题解决、爬虫实战、爬取经典moba游戏英雄列表

  • 799阅读 · 22点赞 · 21收藏

前端开发的发展史:框架与技术栈的演变

  • 980阅读 · 18点赞 · 12收藏

打字通小游戏制作教程:用HTML5和JavaScript提升打字速度

  • 1196阅读 · 31点赞 · 25收藏

扫雷小游戏制作教程:用HTML5和JavaScript打造经典游戏

  • 1040阅读 · 19点赞 · 27收藏

拼图小游戏制作教程:用HTML5和JavaScript打造经典游戏

  • 762阅读 · 10点赞 · 19收藏
  • 23
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

洛可可白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值