wangEditor富文本编辑器使用

一、官网

开源 Web 富文本编辑器,开箱即用,配置简单

二、下载安装

npm install --save @wangeditor/editor-for-vue

三、在vue中使用

3.1、抽离组件editor.vue

在工程的components目录下新建组件editor

javascript 复制代码
<template>
      <div>
        <Toolbar
            :editor="editor"
            :defaultConfig="toolbarConfig"
            :mode="mode"
        />
        <Editor
            v-model="html"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="onCreated"
        />
      </div>
</template>
<script>
import { Base64 } from 'js-base64'
import { Loading, Message } from 'element-ui'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

export default {
  components: { Editor, Toolbar },
  props: {
        html: {
            type: String,
            default: ''
        },
  },
  data() {
    let loading = ''
      return {
        editor: null,
        toolbarConfig: {
          toolbarKeys: [
            // 一些常用的菜单 key
            'bold', // 加粗
            'italic', // 斜体
            'through', // 删除线
            'underline', // 下划线
            'bulletedList', // 无序列表
            'numberedList', // 有序列表
            'color', // 文字颜色
            'insertLink', // 插入链接
            'fontSize', // 字体大小
            'lineHeight', // 行高
            'uploadImage', // 上传图片
            //'uploadVideo',//上传视频
            'delIndent', // 缩进
            'indent', // 增进
            'deleteImage',//删除图片
            'divider', // 分割线
            'insertTable', // 插入表格
            'justifyCenter', // 居中对齐
            'justifyJustify', // 两端对齐
            'justifyLeft', // 左对齐
            'justifyRight', // 右对齐
            'undo', // 撤销
            'redo', // 重做
            'clearStyle', // 清除格式
            //'fullScreen' // 全屏
          ]
        },
        editorConfig: {
          placeholder: '请输入内容...' ,
          MENU_CONF: {
            uploadImage: {
              server: '/api/blade-resource/oss/endpoint/put-file',
              fieldName: 'file',
              // 单个文件的最大体积限制,默认为 2M
              maximgSize: 10 * 1024 * 1024, // 10M
              // 最多可上传几个文件,默认为 100
              maxNumberOfimgs: 10,
              // 选择文件时的类型限制,默认为 ['image/*'] 。如不想限制,则设置为 []
              allowedimgTypes: ['image/*'],
              // 自定义上传参数,例如传递验证的 token 等。参数会被添加到 formData 中,一起上传到服务端。
              meta: {
                // token: 'xxx',
                // otherKey: 'yyy'
                // img:''
              },
              // 将 meta 拼接到 url 参数中,默认 false
              metaWithUrl: false,

              // 自定义增加 http  header
              headers: {
                // Accept: 'text/x-json',
                [website.tokenHeader]: `bearer ${getToken()}`,
                Authorization: `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`
              },

              // 跨域是否传递 cookie ,默认为 false
              withCredentials: true,

              // 超时时间,默认为 10 秒
              timeout: 10 * 1000, //10 秒

              // 上传前
              onBeforeUpload(imgs) {
                loading = Loading.service({
                  lock: true,
                  text: '图片正在上传中,请耐心等待',
                  spinner: "el-icon-loading"
                });
                return imgs;
              },
              // 自定义插入图片
              customInsert(res, insertFn) {
                console.log('customInsert', res)
                // 因为自定义插入导致onSuccess与onFailed回调函数不起作用,自己手动处理
                // 先关闭等待的ElMessage
                loading.close();

                if (res.code === 200) {
                  Message({
                    message: '图片上传成功',
                    type: 'success'
                  })
                } else {
                  Message({
                    message: '图片上传失败,请重新尝试',
                    type: 'error'
                  })
                }
                // 从 res 中找到 url alt href ,然后插入图片
                insertFn(res.data.link);
                // console.log(res, "res.data")
              },

              // 单个文件上传成功之后
              onSuccess(img, res) {
                console.log(`${img.name} 上传成功`, res);
              },

              // 单个文件上传失败
              onFailed(img, res) {
                console.log(`${img.name} 上传失败`, res);
              },

              // 上传进度的回调函数
              onProgress(progress) {
                console.log('progress', progress);
                // progress 是 0-100 的数字
              },

              // 上传错误,或者触发 timeout 超时
              onError(img, err, res) {
                console.log(`${img.name} 上传出错`, err, res);
              }
            }
          }
        },
        mode: 'default', // or 'simple'
      }
  },
  created() {
      if(this.html) {
        this.html = decodeURIComponent(this.html)
      }
  },
  methods:{
    onCreated(editor) {
        this.editor = Object.seal(editor) // 一定要用 Object.seal() ,否则会报错
    },
    beforeDestroy() {
        const editor = this.editor
        if (editor == null) return
        editor.destroy() // 组件销毁时,及时销毁编辑器
    }
  }
}
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>

3.2、使用组件editor.vue

javascript 复制代码
<template>
<div>
    <!--- ... --->
    <editor v-model="html" />
    <!--- ... --->
</div>
</template>

<script>
import Editor from '@/components/editor'
export default {
    components: { Editor },
    data() {
        return {
            html: ''
        }
    }
}
</script>
相关推荐
前端扎啤10 分钟前
高效前端开发:解密pnpm的存储与链接
前端·前端框架·npm·pnpm·依赖
苏十八23 分钟前
前端基础:JavaScript(篇一)
开发语言·前端·javascript·面试·html·ecmascript·html5
BestArsenaI24 分钟前
关于vue创建项目失败报错(镜像过期)的解决方案
npm·vue
narukeu29 分钟前
React 中 useState 和 useReducer 的联系和区别
前端·react.js·前端框架
38kcok9w2vHanx_36 分钟前
v-html 空格/换行不生效
前端·html
shootero@126.com1 小时前
npm常用命令
前端·npm·node.js
余十步1 小时前
Vue整合echarts
前端·vue.js·echarts
QD_ANJING1 小时前
2024年前端面试中面试官常拷打的“项目细节”!
前端·面试·职场和发展
粥里有勺糖2 小时前
「豆包Marscode体验官」MarsCode IDE 搭建 VitePress 博客并使用 GitHub 部署
前端·程序员·github
鱟鲥鳚2 小时前
SpringBoot设置自动跳转前端界面
前端·spring boot·后端