【VUE】16、使用 wangEditor 富文本编辑器

wangEditor 是一款基于 JavaScript 开发的 Web 富文本编辑器,以其开箱即用、配置简单的特点深受开发者喜爱。目前最新版本为 V5,相比之前的版本,V5 进行了彻底的重构,功能更强大,使用更灵活。

1、安装

  • 使用 npm 安装
bash 复制代码
npm install @wangeditor/editor --save
npm install @wangeditor/editor-for-vue --save
  • 使用 yarn 安装
bash 复制代码
yarn add @wangeditor/editor
yarn add @wangeditor/editor-for-vue
  • 安装说明:
  1. @wangeditor/editor 是 wangEditor 的核心库,必须安装
  2. @wangeditor/editor-for-vue 是官方提供的 Vue2 组件封装
  3. ⚠️ 注意:如果是 Vue3 项目,需要安装 @wangeditor/editor-for-vue3;如果是 React 项目,安装 @wangeditor/editor-for-react

2、基本使用

在 Vue2 组件中使用 Editor 和 Toolbar 组件:

html 复制代码
<template>
  <div class="editor-container">
    <!-- 工具栏 -->
    <Toolbar
      :editor="editor"
      :defaultConfig="toolbarConfig"
    />
    <!-- 编辑器 -->
    <Editor
      v-model="content"
      :defaultConfig="editorConfig"
      @onCreated="handleEditorCreated"
    />
  </div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

export default {
  name: 'WangEditor',
  components: { Editor, Toolbar },
  data() {
    return {
      editor: null,
      content: '<p>请输入内容...</p>',
      // 工具栏配置
      toolbarConfig: {
        excludeKeys: [], // 排除某些菜单
      },
      // 编辑器配置
      editorConfig: {
        placeholder: '请输入内容...',
      },
    }
  },
  methods: {
    handleEditorCreated(editor) {
      this.editor = editor // 保存 editor 实例,供后续操作
    },
  },
  // 组件销毁时也销毁编辑器
  beforeDestroy() {
    if (this.editor) {
      this.editor.destroy()
    }
  },
}
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>

3、配置图片上传

实际项目中,通常需要配置图片上传功能。wangEditor V5 提供了 customUpload 自定义上传方法:

html 复制代码
<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

export default {
  // ... 其他配置
  data() {
    return {
      editorConfig: {
        placeholder: '请输入内容...',
        // 自定义上传配置
        MENU_CONF: {
          uploadImage: {
            // 自定义上传
            customUpload: async (file, insertFn) => {
              // file 是选中的文件
              const formData = new FormData()
              formData.append('file', file)
              
              try {
                // 调用后端上传接口
                const res = await this.uploadImageToServer(formData)
                // 插入图片
                insertFn(res.data.url, res.data.alt, res.data.href)
              } catch (error) {
                console.error('上传失败', error)
              }
            },
          },
        },
      },
    }
  },
  methods: {
    async uploadImageToServer(formData) {
      // 示例:使用 axios 上传
      const response = await axios.post('/api/upload', formData)
      return response.data
    },
  },
}
</script>

4、读取和设置内容

javascript 复制代码
// 获取编辑器内容(HTML 格式)
const html = this.editor.getHtml()

// 获取纯文本内容
const text = this.editor.getText()

// 设置内容
this.editor.setHtml('<p>新内容</p>')

5、常用配置项

javascript 复制代码
// 编辑器配置示例
const editor = new E(domElement)

// 设置 z-index
editor.config.zIndex = 100

// 设置菜单
editor.config.menus = [
  'head',  // 标题
  'bold',  // 粗体
  'italic',  // 斜体
  'underline',  // 下划线
  'image',  // 图片
  'code',  // 代码块
  'table',  // 表格
]

// 设置 onChange
editor.config.onchange = (html) => {
  console.log('变化后的 HTML:', html)
}

// 设置 onblur
editor.config.onblur = (html) => {
  console.log('编辑器失焦:', html)
}

editor.create()

6、封装成组件

  • 封装组件
html 复制代码
<!-- WangEditor.vue -->
<template>
  <div class="wang-editor">
    <Toolbar
      v-if="editor"
      :editor="editor"
      :defaultConfig="toolbarConfig"
    />
    <Editor
      v-model="html"
      :defaultConfig="editorConfig"
      @onCreated="handleCreated"
      @onChange="handleChange"
    />
  </div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

export default {
  name: 'WangEditor',
  components: { Editor, Toolbar },
  props: {
    value: {
      type: String,
      default: '',
    },
    placeholder: {
      type: String,
      default: '请输入内容...',
    },
  },
  data() {
    return {
      editor: null,
      html: this.value,
      toolbarConfig: {},
      editorConfig: {
        placeholder: this.placeholder,
      },
    }
  },
  watch: {
    value(newVal) {
      if (newVal !== this.html && this.editor) {
        this.editor.setHtml(newVal)
      }
    },
    html(newVal) {
      this.$emit('input', newVal)
    },
  },
  methods: {
    handleCreated(editor) {
      this.editor = editor
    },
    handleChange(editor) {
      this.$emit('change', editor.getHtml())
    },
  },
  beforeDestroy() {
    if (this.editor) {
      this.editor.destroy()
    }
  },
}
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>
  • 使用组件
html 复制代码
<template>
  <WangEditor v-model="content" placeholder="请输入文章内容" />
</template>

<script>
import WangEditor from '@/components/WangEditor.vue'

export default {
  components: { WangEditor },
  data() {
    return {
      content: '',
    }
  },
}
</script>

如您在阅读中发现不足,欢迎留言!!!

相关推荐
一 乐2 小时前
学院教学工作量统计|基于java+ vue学院教学工作量统计管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·学院教学工作量统计系统
布局呆星3 小时前
Vue Router 笔记(二):正则路由、组件通信与动态路由
前端·javascript·vue.js
hexu_blog4 小时前
前端vue后端springboot如何实现图片格式转换
前端·javascript·vue.js
代码煮茶4 小时前
Vue3 项目规范实战 | ESLint+Prettier+Git Hooks 搭建前端代码规范体系
前端·javascript·vue.js
hexu_blog5 小时前
前端vue 后端springboot如何实现图片去水印
前端·javascript·vue.js
spmcor5 小时前
前端 RBAC 权限控制实战:从零实现动态路由与细粒度按钮权限
vue.js
spmcor5 小时前
Vue 2 vs Vue 3:核心差异深度剖析与迁移指南
vue.js
Asurplus6 小时前
【VUE】17、使用JSEncrypt对数据加解密
javascript·vue.js·jsencrypt·rsa
hexu_blog19 小时前
vue+java实现图片批量压缩
java·前端·vue.js