在 Vue3 中使用 WangEditor 富文本编辑器

WangEditor 是一款轻量级、开源的 Web 富文本编辑器,非常适合在 Vue 项目中使用。以下是完整的集成指南:

1. 安装 WangEditor

bash

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

2. 基础使用示例

组件形式 (推荐)

vue

<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      style="border-bottom: 1px solid #ccc"
    />
    <Editor
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      style="height: 500px; overflow-y: hidden"
      @onCreated="handleCreated"
    />
  </div>
</template>

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

// 编辑器实例,必须用 shallowRef
const editorRef = shallowRef()

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

// 工具栏配置
const toolbarConfig = { excludeKeys: ['uploadImage'] }

// 编辑器配置
const editorConfig = { placeholder: '请输入内容...' }

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

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例
}
</script>

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

传统 API 形式

javascript

import { createEditor, createToolbar } from '@wangeditor/editor'

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

const editor = createEditor({
  selector: '#editor-container',
  config: editorConfig,
  html: '<p><br></p>',
})

const toolbar = createToolbar({
  editor,
  selector: '#toolbar-container',
  config: {},
})

3. 常用配置选项

工具栏配置

javascript

const toolbarConfig = {
  // 排除菜单键
  excludeKeys: [
    'headerSelect',
    'italic',
    'group-more-style' // 排除菜单组
  ],
  
  // 插入键配置
  insertKeys: {
    index: 5, // 插入的位置,基于当前的 toolbarKeys
    keys: ['uploadImage']
  }
}

编辑器配置

javascript

const editorConfig = {
  placeholder: '请输入内容...',
  autoFocus: false,
  scroll: true,
  readOnly: false,
  
  // 图片上传配置
  MENU_CONF: {
    uploadImage: {
      server: '/api/upload',
      fieldName: 'your-file-field-name',
      maxFileSize: 10 * 1024 * 1024, // 10M
      allowedFileTypes: ['image/*'],
      timeout: 30 * 1000, // 30秒
    }
  }
}

4. 自定义功能扩展

注册自定义菜单

javascript

import { Boot } from '@wangeditor/editor'

class MyMenu {
  title = '我的菜单'
  tag = 'button'
  
  getValue(editor) {
    return ''
  }
  
  isActive(editor) {
    return false
  }
  
  isDisabled(editor) {
    return false
  }
  
  exec(editor, value) {
    if (this.isDisabled(editor)) return
    alert('我的菜单被点击了')
  }
}

Boot.registerMenu({
  key: 'myMenu', // 菜单 key ,唯一
  factory() {
    return new MyMenu()
  },
})

自定义插件

javascript

import { DomEditor } from '@wangeditor/editor'

const plugin = {
  onEditorCreated(editor) {
    // 编辑器创建后触发
  },
  
  onEditorChange(editor) {
    // 编辑器内容变化时触发
  },
  
  onEditorDestroyed(editor) {
    // 编辑器销毁时触发
  }
}

Boot.registerPlugin(plugin)

5. 常见问题解决

样式问题

确保正确引入 CSS:

javascript

import '@wangeditor/editor/dist/css/style.css'

SSR 兼容

在 Nuxt.js 等 SSR 框架中使用:

javascript

// 只在客户端加载
if (process.client) {
  const { Boot } = require('@wangeditor/editor')
  // 初始化代码...
}

图片上传示例

javascript

editorConfig.MENU_CONF = {
  uploadImage: {
    server: '/api/upload',
    fieldName: 'file',
    maxFileSize: 10 * 1024 * 1024,
    allowedFileTypes: ['image/*'],
    
    // 自定义上传
    customUpload(file, insertFn) {
      // 自己实现上传逻辑
      const formData = new FormData()
      formData.append('file', file)
      
      axios.post('/api/upload', formData)
        .then(res => {
          insertFn(res.data.url, res.data.alt, res.data.href)
        })
    }
  }
}

6. 最佳实践

  1. 性能优化:对于频繁更新的内容,使用 shallowRef 存储编辑器实例

  2. 安全考虑:渲染 HTML 内容时使用 DOMPurify 进行净化

  3. 类型提示:在 TypeScript 项目中安装 @wangeditor/editor 的类型定义

  4. 版本控制:锁定 wangEditor 版本以避免意外升级带来的问题

7. 官方资源

通过以上指南,您应该能够在 Vue3 项目中顺利集成和使用 WangEditor 富文本编辑器。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐