简单的记录一下 wangEditor 5 在vue中使用

367 阅读1分钟

记录

在vue2.7上使用的, 一开始官方文档没看明白, 感觉配置复杂, 基础差, 看不懂, 但是最后还是磕磕绊绊用下来了, 简单的记录一下

安装

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

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

引入样式

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

简单的改造

主要是自定义上传图片和视频

一开始官方文档没看明白

<template>
  <div>
    <Toolbar style="border-bottom: 1px solid #ccc"
             :editor="editor"
             :defaultConfig="richTextConfig.toolbar"
             :mode="richTextConfig.mode"
    />
    <Editor style="height: 500px; overflow-y: hidden;"
            v-model="editorContent"
            :defaultConfig="richTextConfig.editorConfig"
            :mode="richTextConfig.mode"
            @onCreated="onCreated"
            @onChange="onChangeHandler"
    />
    <div>输出: {{ editorContent }}</div>
  </div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import {onBeforeUnmount, reactive, ref, toRefs} from "vue";

export default {
  name: "RichTextEditor",
  components: {Editor, Toolbar},
  setup(){
    const richTextInteraction = function (){
      const editor = ref(null)
      const unFullScreen = ref(true)
      const editorContent = ref('')

      // eslint-disable-next-line no-unused-vars
      const uploadImg = function (file, insert){
        // 自定义图片上传方法 ...
        // insert(url) 插入上传后的图片的链接
      }
      // 自定义插入图片方法
      const insertImg = function (){
        // ...
      }
      // eslint-disable-next-line no-unused-vars
      const uploadVideo = function (file, insert){
        // ... 自定义上传视频方法
        // insert(url) 插入上传后的视频的链接
      }
      const richTextConfigReactive = reactive({
        mode: 'default', // or 'simple'
        toolbar: {

        },
        editorConfig: {
          placeholder: '请输入内容...',
          MENU_CONF: {
            uploadImage: {
              // 自定义上传图片 方法
              customUpload: uploadImg,
              // 自定义插入图片 方法
              customInsert: insertImg,
            },
            uploadVideo: {
              customUpload: uploadVideo,
            }
          }
        }
      })
      const richTextConfig = toRefs(richTextConfigReactive)

      const onCreated = function (editorGen) {
        // 一定要用 Object.seal() ,否则会报错
        editor.value = Object.seal(editorGen)
      }

      const onChangeHandler = function (){

      }

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

      return {
        editor,
        unFullScreen,
        richTextConfig,
        editorContent,
        onCreated,
        onChangeHandler,
      }
    }
    return {
      ...richTextInteraction()
    }
  }
}
</script>

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

</style>

效果

image.png